Reputation: 7030
I have a 4 byte hexadecimal code of a string type that I need to convert into a float, conforming to the IEEE 754 Single-Precision floating-point format.
I think Java had a library to do this with ease but I'm not sure if C# has one. What is the best way to approach this problem?
Upvotes: 2
Views: 4795
Reputation: 1063328
Since it sounds like you're starting from a hex string:
string hex = "0a0b0c0d";
byte[] raw = new byte[hex.Length / 2];
for (int i = 0; i < raw.Length; i++)
{
// THEN DEPENDING ON ENDIANNESS
raw[i] = Convert.ToByte(hex.Substring(i * 2, 2), 16);
// OR
raw[raw.Length - i - 1] = Convert.ToByte(hex.Substring(i * 2, 2), 16);
}
float f = BitConverter.ToSingle(raw, 0);
If you are actually starting from a byte[]
, then you can skip the first few steps.
Upvotes: 6