1
\$\begingroup\$

I'm assigning a HEX-Value to a byte in a byte array and then send this byte array to a serial port. If the value is bigger than 255 the corresponding HEX-Value is supposed to be split into two.

Example: 750 = 0x2EE so A[0] = 0x2 and A[1] = 0xEE

Is this an efficient way to do the task that I want it to do? From what I read so far the conversion should be okay here or can I skip the 0x and still get the same result after the Convert.ToByte?

    private void button3_Click(object sender, EventArgs e)
    {
        byte[] A = new byte[2];
        string f = "0x" + Convert.ToInt32(textBox3.Text).ToString("X");
        textBox2.Text = Convert.ToString(f.Length);  //to test length
        if (f.Length < 5)
        {
            A[0] = 0x00;
            A[1] = Convert.ToByte(f,16);
            textBox1.Text = "A";
        }
        else if (f.Length == 5)
        {
            A[0] = Convert.ToByte(f.Substring(0,3),16);
            A[1] = Convert.ToByte("0x" + f.Substring(3),16);
            textBox1.Text = "B" + "Sub0: " + f.Substring(0, 3) + "\r\n Sub1 :" + "0x" + f.Substring(3); //to test
        }
        else
        {
            textBox1.Text = "Falsche Eingabe";
        }      
    }
\$\endgroup\$
1
\$\begingroup\$

Why try and manipulate the number as a string?

Personally I would convert the input to a number and then manipulate it and finally convert it back to a string, if you need to. However I would have thought C# has a way of making a text box accept Hex numbers and returning an Int (I don't know I don't do GUIs.)

Using your example number 0x2ee. If the number if greater than 0xFF then it will take more than one byte to store it. So to split the value you can do lowerByte = number % 256. The upper byte is simply upperByte = (number - lowerByte) >> 8

So putting this into code

static byte[] SplitNumber (Int16 number)
{
    byte[] returnValue = new byte[2];
    returnValue[0] = Convert.ToByte(number % 256);
    returnValue[1] = Convert.ToByte((number - returnValue[0]) >> 8);
    return returnValue;
}

Now you have your bytes, you can format them in the text box as you like,

\$\endgroup\$
  • \$\begingroup\$ Did you mean to use the & and not the % modulo operator? With % you'll get 0xF0 = 240 which is invalid. \$\endgroup\$ – t3chb0t Dec 12 '16 at 13:58

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.