ex0ff
ex0ff

Reputation: 25

Converting IEEE 754 float to hex string

I have this code that converts hex to float i basically need the reverse of this operation

byte[] bytes = BitConverter.GetBytes(0x445F4002);
float myFloat = BitConverter.ToSingle(bytes, 0);
MessageBox.Show(myFloat.ToString());

I want to enter the float and turn it to hex string.

Upvotes: 0

Views: 2866

Answers (1)

David Heffernan
David Heffernan

Reputation: 613232

  1. Call BitConverter.GetBytes to get a byte array representing your float.
  2. Convert the byte array to hex string: How do you convert Byte Array to Hexadecimal String, and vice versa?

FWIW, the code in your question does not do the reverse of this. In fact the code in your question does not receive a hex string. It receives an int literal that you expressed as hex. If you wish to convert from a hex string to a float then you use the code in the link above to convert from hex string to byte array. And then you pass that byte array to BitConverter.ToSingle.


It seems you are having problems putting this together. This function, taken from the question I link to above, converts from byte array to hex string:

public static string ByteArrayToString(byte[] ba)
{
  StringBuilder hex = new StringBuilder(ba.Length * 2);
  foreach (byte b in ba)
    hex.AppendFormat("{0:x2}", b);
  return hex.ToString();
}

Call it like this:

string hex = ByteArrayToString(BitConverter.GetBytes(myfloat));

And in comments you state that you wish to reverse the bytes. You can find out how to do that here: How to reverse the order of a byte array in c#?

Upvotes: 3

Related Questions