Vivian
Vivian

Reputation: 1061

How to dynamically adjust the length of a message based on the second byte entry from a string of byte entries?

Assuming my second byte in hex is a representation of the message length, how can I dynamically adjust the length of the message the user can key into the textbox based on the hex value of the second byte?

Message Byte entries: xx xx xx xx xx xx xx xx xx xx xx xx ..... where x is 0-9, a-f.

The code below was used as a sort of my goal keeper to allow only hex entry into the textbox but I want to further enhance the code below with additional function mention above? Sorry if I couldn't explain it clearly enough due to my inadequate English command. Thanks

void textBox1_TextChanged(object sender, EventArgs e)
{
    int caret = textBox1.SelectionStart;
    bool atEnd = caret == textBox1.TextLength;
    textBox1.Text = sanitiseText(textBox1.Text);
    textBox1.SelectionLength = 0;
    textBox1.SelectionStart = atEnd ? textBox1.TextLength : caret;
}

void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
    if (!isHexDigit(e.KeyChar) && e.KeyChar != '\b')
        e.Handled = true;
}

string sanitiseText(string text)
{
    char[] result = new char[text.Length*2];

    int n = 0;

    foreach (char c in text)
    {
        if ((n%3) == 2)
            result[n++] = ' ';

        if (isHexDigit(c))
            result[n++] = c;
    }

    return new string(result, 0,  n);
}

bool isHexDigit(char c)
{
    return "0123456789abcdef".Contains(char.ToLower(c));
}

Upvotes: 0

Views: 102

Answers (1)

oziomajnr
oziomajnr

Reputation: 1741

First of all, have a method to convert the hex to dec. Then on your data recieived event, convert the second byte of your packet to decimal and set the MaxLenght property of the textbox equal to the size of the second byte. If you are not using events, then you can do it immediately after reading the data.

Upvotes: 1

Related Questions