Floating point bit layout

  • Thread starter Thread starter n!
  • Start date Start date
N

n!

I'd like to obtain the bit layout of a single-precision, floating point
value. ie. I'd like to convert the 32bit float to a 32bit [unsigned]
integer, not the value but the binary contents.

For those familiar with C++, I'd like something similar to:

unsigned int ExtractBits( float value )
{
return *reinterpret_cast< unsigned int* >( &value );
}

I'd like to avoid 'unsafe' code so I can't use a similar (take the address
and cast it to something else) hack. An alternative I can think of is to
create a memory stream, write the float into it and read it back as an
integer (which is a variation on the above). But that seems a bit icky...

I'd also like this conversion both ways, so I can convert from a float to an
integer and back again to a float.

Thanks,
n!
 
n!

You might want to try the BitConverter class. You can call the static
GetBytes method on the class to get the byte representation of the float (in
four bytes). From there, you can call the static ToUInt32 method to get the
unsigned integer representation.

Hope this helps.
 
You might want to try the BitConverter class. You can call the static
GetBytes method on the class to get the byte representation of the float (in
four bytes). From there, you can call the static ToUInt32 method to get the
unsigned integer representation.

Ahh that sounds familiar now you mention it! And it does indeed do exactly
what I wanted.

Many thanks,
n!
 
Back
Top