2
votes

I'm sure there's something I'm missing. I use this code:

int bitsVal = Float.floatToIntBits(f);
String bitsString = Integer.toString(bitsVal, 2);

This seems to work fine for positive numbers. I mean, the string must be left-padded with zeros to get the whole 32 bits representation, but otherwise, it's fine.

For exampele for f=2.085 i get:

bitsString=100 0000 0000 0101 0111 0000 1010 0100

(i've added the spaces myself for clarity, they're not really there)

There's only 31 ones and zeros there because the first bit would be the sign bit, which in this case is 0, so if i just left-pad it with 0 till i get 32 elements is ok.

Same goes for f=0.85 which gives:

bitsString=11 1101 1010 1110 0001 0100 0111 1011

which is fine again, because the 2 first missing bits are 0 (again, for the sign), and again 0 because the binary representation of the normalized exponent is 01111011.

But for negative values I get really strange values. From what I understand, if a given positive value for f gives the IEEE 754 (single precision) representation of 0xxxxxx (0 followed by 31 bits for the normalized exponent and mantissa), then negative f would return the same sequence save for the first bit on the left which changes from 0 to 1.

But with the code above, for f=-0.85 i get

bitsString = -100 0010 0101 0001 1110 1011 1000 0101

which, save for the "-" (minus char) which should be a "1" ( I guess) has strange values.

So my question is, is there a way, using the Java APIs to get the IEEE 754 (single precision) bit sequence for a given floating point number (other than rolling my own, which I already did)?

Thanx

1

1 Answers

3
votes

The problem is that int in Java is signed. When you do Integer.toString(bitsVal, 2); you're not displaying the literal bits of bitsVal, you're displaying the base-two representation of the signed integer that those bits represent (i.e. Integer.toString((int)0xFFFFFFFF, 2) would produce -1).

But Integer.toBinaryString(bitsVal) treats the value as an unsigned 32 bit integer, so should produce that result you're after (Integer.toBinaryString((int)0xFFFFFFFF) would produce a string of 32 1's).