0

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.

  • Not entirely sure what you are starting with and where you are trying to go, but you can parse a hex string with `int.Parse("417D", NumberStyles.AllowHexSpecifier);` You can then use `GetBytes` and `BitConverter` as in your second code snippet. – Matt Burland Jan 05 '16 at 16:08
  • 1
    Hexadecimal is a **representation**. What do you mean by "preserving the hex number"? What _exactly_ is your question? _"How to convert two hexadecimal strings to a `single`"_? – CodeCaster Jan 05 '16 at 16:20

1 Answers1

1

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
Matt Burland
  • 44,552
  • 18
  • 99
  • 171