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

Assuming that my second byte in hexadecimal represents the length of the message, how can I dynamically adjust the length of the message that the user can enter in the text box based on the hexadecimal value of the second byte

Records of the message byte: xx xx xx xx xx xx xx xx xx xx xx xx ..... where x is 0-9, af.

The code below was used as my goal keeper to allow only hexadecimal writing to the text field, but I want to further improve the code below with the additional mention above. Sorry if I canโ€™t explain it clearly enough because of my inadequate English team. 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));
}
0
source share
1 answer

First of all, I have a method for converting hex to dec. Then, in your event returned, convert the second byte of your packet to decimal and set the MaxLenght property of the text field to the size of the second byte. If you are not using events, you can do this immediately after reading the data.

+1
source

All Articles