Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Value of 1024 has one bit more in binary representation that value of 1

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?

like image 933
Piotr Müller Avatar asked Mar 25 '23 00:03

Piotr Müller


2 Answers

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

like image 69
Peter Lawrey Avatar answered Apr 19 '23 11:04

Peter Lawrey


Try this:

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

The output is:

1

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

like image 26
Eng.Fouad Avatar answered Apr 19 '23 11:04

Eng.Fouad