Search code examples
c#stringhexbitconverter

Passing a hex string in a textbox.text property to BitConverter.GetBytes as hex in C#


I am reading values from sensors and receiving two 16 bit Hex values back in string format "417D" and "8380" for example.

I cannot seem to find a way in C# to parse the strings to split them up into a byte array ( 41,7D,83,80 ) preserving the hex number.

I then use the following to convert the IEEE754 number to a decimal to get the correct sensor reading value.

txtFloatValue.Text = BitConverter.ToSingle(hex, 0).ToString();

The code below works, but I need to pass the values as a hex array, not 0x417D8380.

byte[] hex = BitConverter.GetBytes(0x417D8380);
txtFloatValue.Text = BitConverter.ToSingle(hex, 0).ToString();

Any advice would be much appreciated. I may be approaching this the wrong way, but the IEEE754 conversion works well.


Solution

  • You can parse your hex strings to ints and then use BitConverter. For example:

    var i = int.Parse("417D8380", NumberStyles.AllowHexSpecifier);
    var bytes = BitConverter.GetBytes(i);
    var single = BitConverter.ToSingle(bytes, 0);   // 15.8446