In C I will do this to convert float representation of number into DWORD. Take the value from the address and cast the content to DWORD.
dwordVal = *(DWORD*)&floatVal;
So for example 44.54321
will become 0x42322C3F
.
How can I do the same in C#
?
Since a float is bigger than int, you can convert a float to an int by simply down-casting it e.g. (int) 4.0f will give you integer 4. By the way, you must remember that typecasting just get rid of anything after the decimal point, they don't perform any rounding or flooring operation on the value.
Method 1: Conversion using int(): To convert a float value to int we make use of the built-in int() function, this function trims the values after the decimal point and returns only the integer/whole number part.
Python also has a built-in function to convert floats to integers: int() . In this case, 390.8 will be converted to 390 .
round() method, which converts float to its nearest integer by adding +0.5 to it's value and then truncating it.
You can use the BitConverter
class:
uint value = BitConverter.ToUInt32(BitConverter.GetBytes(44.54321F), 0);
Console.WriteLine("{0:x}", value); // 42322c3f
You could also do this more directly using an unsafe
context:
float floatVal = 44.54321F;
uint value;
unsafe {
value = *((uint*)(&floatVal));
}
Console.WriteLine("{0:x}", value); // 42322c3f
However, I'd strongly recommend avoiding this. See Should you use pointers (unsafe code) in C#?
Use the BitConverter class:
float f = 44.54321f;
uint u = BitConverter.ToUInt32(BitConverter.GetBytes(f), 0);
System.Diagnostics.Debug.Assert(u == 0x42322C3F);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With