/home/wpollock1/public_html/restricted/Java1/ShowDoubleBits.java
// A Java program that shows the representation of Java doubles for
// various values. Adopted from a post by Stefan Ram <ram@zedat.fu-berlin.de>
// titled "double bits" in the newsgroup comp.lang.java.programmer
// on 2 May 2017.
//
// The format (encoding) of doubles is from the IEEE-754 standard, which is
// mostly straight-forward. Number the 64 bits from 63 (leftmost) to 0. Then:
// s The sign is bit 63: 0=positive, 1=negative
// e The exponent is bits 62-52, encoding with an exponent of zero at 1023.
// (So if the exponent is 1, it is encoded as the number 1024.)
// m The significand a.k.a. the mantissa is bits 51-0, but with an assumed
// extra bit of "1" at the left, giving 53 bits total. Note, special values
// of zero, Infinity, and NaN have the extra bit as "0" instead.
//
// Adopted by Wayne Pollock, Tampa Florida USA
public class ShowDoubleBits {
public static void main ( String[] args ) {
showBits( 1.0 );
showBits( 2.0 );
showBits( 3.0 );
showBits( 4.0 );
showBits( 5.0 );
showBits( 6.0 );
showBits( 8.0 );
showBits( 0.1 );
showBits( -1.0 );
showBits( -2.0 );
showBits( -3.0 );
showBits( -4.0 );
showBits( -5.0 );
showBits( -6.0 );
showBits( -7.0 );
showBits( -8.0 );
showBits( -0.1 );
showBits( 256.0 );
showBits( 32768.0 );
showBits( -256.0 );
showBits( -32768.0 );
showBits( +0.0 );
showBits( -0.0 );
showBits( +1/0. );
showBits( -1/0. );
showBits( 0/0. );
}
private static void showBits ( final double x ) {
System.out.printf( "%9.1f: ", x ); // Print original double normally
long bits = Double.doubleToRawLongBits( x );
// Extract the sign (s), exponent (e), and mantissa (m):
int s = ((bits >> 63) == 0) ? 0 : 1; // Left-most bit (63)
int e = (int)((bits >> 52) & 0x7ffL); // Next 11 bits (62-52)
String eStr =
String.format("%11s", Integer.toBinaryString(e)).replace(' ', '0');
// Calculate the extra "hidden" 53rd bit correctly as zero or one:
long m = (e == 0) ?
(bits & 0xf_ffff_ffff_ffffL) << 1 :
(bits & 0xf_ffff_ffff_ffffL) | 0x10_0000_0000_0000L;
String mStr = String.format("%53s",
Long.toBinaryString(m)).replace(' ', '0') ;
System.out.printf( "%d-%s-%s%n", s, eStr, mStr );
}
}