7

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

phuclv
  • 37,963
  • 15
  • 156
  • 475
Pablo
  • 28,133
  • 34
  • 125
  • 215
  • 3
    Actually `*(DWORD*)&floatVal` is the wrong way to do it in C as it breaks strict aliasing rules that C compilers rely on for optimisation. Correct ways involve a union (see C99tc3 footnote 82) or `memcpy()`. – Pascal Cuoq Feb 15 '14 at 22:53

4 Answers4

13

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

Community
  • 1
  • 1
p.s.w.g
  • 146,324
  • 30
  • 291
  • 331
3

Use the BitConverter class:

float f = 44.54321f;
uint u = BitConverter.ToUInt32(BitConverter.GetBytes(f), 0);
System.Diagnostics.Debug.Assert(u == 0x42322C3F);
MarcinJuraszek
  • 124,003
  • 15
  • 196
  • 263
Hans Passant
  • 922,412
  • 146
  • 1,693
  • 2,536
1

In .NET Core 2.0 you can use BitConverter.SingleToInt32Bits(). The reverse operation is BitConverter.Int32BitsToSingle()

.NET 6 added 2 more utilities:

phuclv
  • 37,963
  • 15
  • 156
  • 475
0

bitconvert creates a new byte array on every call. this is the solution:

    unsafe public static float ToDecibel(this float x)
    {
        uint* y = (uint*)&x;
        (*y) &= 0x7fffffff;
        return (*y) * 7.17711438e-7f - 764.6161886f;
    }
  • +1 for remembering `unsafe`. BUT ... This changes `x`! Better to use `uint y = *(uint*)&x; y &= 0x7fffffff; return y * 7.17711438e-7f - 764.6161886f;` to avoid changing `x`. – Jesse Chisholm Apr 16 '22 at 14:57