How to convert float to uint using float view?

In C I will do this to convert the float representation of a number to a DWORD. Take the value from the address and pass the content to DWORD.

 dwordVal = *(DWORD*)&floatVal; 

So for example 44.54321 will become 0x42322C3F .

How can I do the same in C# ?

+7
floating-point c # int
source share
2 answers

You can use the BitConverter class:

 uint value = BitConverter.ToUInt32(BitConverter.GetBytes(44.54321F), 0); Console.WriteLine("{0:x}", value); // 42322c3f 

You can also do this more directly using the unsafe context :

 float floatVal = 44.54321F; uint value; unsafe { value = *((uint*)(&floatVal)); } Console.WriteLine("{0:x}", value); // 42322c3f 

However, I would highly recommend avoiding this. See Should pointers (unsafe code) be used in C #?

+12
source share

Use the BitConverter class:

 float f = 44.54321f; uint u = BitConverter.ToUInt32(BitConverter.GetBytes(f), 0); System.Diagnostics.Debug.Assert(u == 0x42322C3F); 
+3
source share

All Articles