Reputation: 2581
Given the following variable:
float myFloat = 0xC0451EB8;
How do I get C0451EB8 from myFloat?
Edit: Not sure why I am being down voted here with no comment. I am not asking a simple hex representation of a float or uint32. I can do this. Given the variable definition above and a [possible common] answer of:
string FloatAsHex(float myFloat) {
return BitConverter.ToString(BitConverter.GetBytes(myFloat));
}
FloatToHex(0xC0451EB8); //will output 1F-45-40-4F, not what I expect
FloatToHex(BitConverter.ToSingle(BitConverter.GetBytes(0xC0451EB8))) //works
Although the second one obviously works, I only have access to the float variable.
Upvotes: 1
Views: 4500
Reputation: 70691
There is no way to accomplish what you're asking. Your code is storing the integer value 0xC0451EB8
, or in decimal 3225755320
, in a variable of type float
. The integer value has 32 bits of precision, but a float
cannot represent 32 bits of numeric precision, because some of the 32 bits of the float
value are committed to the exponent.
Thus, the integer value 3225755320
gets truncated to 3225755392
.
You can cast the float
back to uint
, and then use the standard mechanism for formatting as a hexadecimal string value. E.g. ((uint)myFloat).ToString("X")
. But when you do that, you'll be starting with the truncated value, and the output will be "C0451F00"
(or "0xC0451F00"
if you include the standard hex specifier prefix in your format string).
Once you truncate the original value, there is no way to recover it. You cannot reverse the process.
Upvotes: 1
Reputation: 119
The documentation says to use BitConverter.ToString Method (Byte[])
on msdn
This will return a string representation of the number in hex base. Example (for array of bytes representing a number):
00-01-02-04-08-10-20-40-80-FF
Upvotes: 0