-1

I’m trying to understand how floating point works. When I run this code :

float number = 3.0f;
int bits = Float.floatToIntBits(number);
System.out.println(Integer.toBinaryString(bits));

I get :

1000000010000000000000000000000 

But the correct binary format for 3 should be (according to  this converter):

01000000010000000000000000000000

Why isn’t the sign bit (0) displayed by println here?

EDIT : initially, I was usingLong.toBinaryString instead of Integer.toBinaryString

I would get this kind of result :

float number = -3.0f;
int bits = Float.floatToIntBits(number);
System.out.println(Long.toBinaryString(bits));

output :

1111111111111111111111111111111111000000010000000000000000000000

but using Integer.toBinaryString return the correct binary format for -3.0f :

11000000010000000000000000000000
comingstorm
  • 23,012
  • 2
  • 38
  • 64
Albizia
  • 325
  • 5
  • 15
  • 4
    It's just `Long.toBinaryString()` dropping the 0 in front. You can see that there's one digit less than in the one you got from the converter. Nothing wrong with the conversion, you're just displaying it wrong. – Kayaman Aug 01 '18 at 08:13
  • Cannot vote for duplicate since it's closed, but this question is actually a duplicate of this one: https://stackoverflow.com/questions/4421400/how-to-get-0-padded-binary-representation-of-an-integer-in-java – fabian Aug 08 '18 at 10:12

2 Answers2

1

Integer::toBinaryString will not add zeros up to 32 bits.

int x = 0b_000001;
System.out.println(Integer::toBinaryString(x));

The result is 1, not 000...0001. (32bits) The heading zeros are omitted.

zhh
  • 1,901
  • 1
  • 7
  • 17
0

That just needed a bit of formatting :

float number = 3.0f;
int bits = Float.floatToIntBits(number);
String representation = Integer.toBinaryString(bits);
representation = String.format("%32s", representation).replace(' ', '0');
Albizia
  • 325
  • 5
  • 15