Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I display the binary representation of a float or double?

I'd like to display the binary (or hexadecimal) representation of a floating point number. I know how to convert by hand (using the method here), but I'm interested in seeing code samples that do the same.

Although I'm particularly interested in the C++ and Java solutions, I wonder if any languages make it particularly easy so I'm making this language agnostic. I'd love to see some solutions in other languages.

EDIT: I've gotten good coverage of C, C++, C#, and Java. Are there any alternative-language gurus out there who want to add to the list?

like image 403
Bill the Lizard Avatar asked Dec 29 '08 13:12

Bill the Lizard


People also ask

How do you represent a float in binary?

This allows the way that the bits are allocated to vary so that both very large and very small numbers can be represented. Binary floating point numbers are expressed in the form mantissa × 2, start superscript, e, x, p, o, n, e, n, t, end superscript,2exponent, e.g. 0, point, 101,0.101 x 2, to the power 4 ,24.

How do you represent a double in binary?

There are 64 bits to represent a double (compared to 32 for int). The sign is represented by a bit this time (1 for "-" and 0 for "+"). The exponent is an 11-bit binary number, but is stored as a "positive" number in the range 0.. 2047 for which 1023 must be subtracted to get the true exponent.

How do you display binary?

To print binary representation of unsigned integer, start from 31th bit, check whether 31th bit is ON or OFF, if it is ON print “1” else print “0”. Now check whether 30th bit is ON or OFF, if it is ON print “1” else print “0”, do this for all bits from 31 to 0, finally we will get binary representation of number.


2 Answers

C/C++ is easy.

union ufloat {   float f;   unsigned u; };  ufloat u1; u1.f = 0.3f; 

Then you just output u1.u. You can adapt this implementation.

Doubles just as easy.

union udouble {   double d;   unsigned long u; } 

because doubles are 64 bit.

Java is a bit easier: use Float.floatToRawIntBits() combined with Integer.toBinaryString() and Double.doubleToRawLongBits combined with Long.toBinaryString().

like image 120
cletus Avatar answered Sep 30 '22 18:09

cletus


In C:

int fl = *(int*)&floatVar; 

&floatVar would get the adress memory then (int*) would be a pointer to this adress memory, finally the * to get the value of the 4 bytes float in int. Then you can printf the binary format or hex format.

like image 33
bslima Avatar answered Sep 30 '22 18:09

bslima