0

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.

Mohit S
  • 13,723
  • 6
  • 34
  • 69
ex0ff
  • 25
  • 1
  • 5

1 Answers1

3
  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#?

Community
  • 1
  • 1
David Heffernan
  • 601,492
  • 42
  • 1,072
  • 1,490
  • No, i need to convert the float to hex – ex0ff Sep 26 '14 at 16:46
  • I know. That's clear from your question title. And you just need to follow the steps in my answer. – David Heffernan Sep 26 '14 at 16:47
  • would you please show me a piece of code that applies to your answer i am not that good dealing with bytes – ex0ff Sep 26 '14 at 16:49
  • OK, I did that. But I do believe that you could have done so yourself. Did you click on the link in my answer? – David Heffernan Sep 26 '14 at 16:50
  • Okay i did it BitConverter.GetBytes(831.00001); string hex = BitConverter.ToString(BitConverter.GetBytes((float)893.0001)); now the result is 02-40-5F-44 i want to get it reversed and w/o the dashes (445F4002) – ex0ff Sep 26 '14 at 16:52
  • 1
    Did you read my answer yet? Did you read the code in it? If you want to reverse the bytes, reverse the bytes. – David Heffernan Sep 26 '14 at 16:57