4

The output of following code:

System.out.println( Long.toBinaryString( Double.doubleToRawLongBits( 1 ) ) );
System.out.println( Long.toBinaryString( Double.doubleToRawLongBits( 1024 ) ) );

Is:

11111111110000000000000000000000000000000000000000000000000000
100000010010000000000000000000000000000000000000000000000000000

Why this code prints one bit more for value of 1024?

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
Piotr Müller
  • 5,323
  • 5
  • 55
  • 82

2 Answers2

4

Why this code prints one bit more for value of 1024?

This is because leading 000000's are dropped by Long.toBinaryString. A double is always 64-bit, but it can have up to 63 leading zeros.

e.g. 000000000000000000000000000000000000000000000000000000000000000000000001 is printed as 1

Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
3

Try this:

System.out.println(Long.toBinaryString(1));

The output is:

1

which indicates that Long.toBinaryString() discards the leading zeros.

Eng.Fouad
  • 115,165
  • 71
  • 313
  • 417