The Java Program: TestFloat.java

  1 // TestFloat.java -- illustrate 32 bit IEEE 754 floating point
  2 
  3 class TestFloat {
  4 
  5    final static int bias = (1<<(8-1)) -1;
  6 
  7    // convert 32 bits to char array of '0' or '1'
  8    public static char [] toChars (int l) {
  9       final char [] s = new char [32];
 10       for (int i=0; i<32; i++) {
 11          s[32-i-1] = (l&0x1)==1?'1' : '0';  // don't use n%2 when n<0!
 12          l >>>= 1;   // shift right logical
 13       }
 14       return (s);
 15    }
 16 
 17    // print representation of IEEE 754 floating-point number
 18    public static void printBits (float d) {
 19       final int b = Float.floatToIntBits (d);
 20       final char [] bits = toChars (Float.floatToIntBits (d));
 21       System.out.format ("f = %f %s %08x  %s%n", d, Float.toString(d), b, Float.toHexString(d));
 22       System.out.println ("sign bit           = " + new String(bits,0, 1));
 23       System.out.println ("exponent (8  bits) = " + new String(bits,1, 8));
 24       System.out.println ("mantissa (23 bits) = " + new String(bits,9,23));
 25       System.out.println ();
 26    }
 27 
 28    public static void main (String args[]) {
 29       printBits (Float.NaN);
 30       printBits (Float.POSITIVE_INFINITY);
 31       printBits (Float.NEGATIVE_INFINITY);
 32       printBits (0.0F);
 33       printBits (-0.0F);
 34       printBits (1.0F);
 35       printBits (-1.0F);
 36       printBits (0x0.01p0F);         // Takes a lot of decimal digits
 37       printBits (0.1F);              // Decimal not representable
 38       printBits (Float.MAX_VALUE);   // Largest value (positive)
 39       printBits (-Float.MAX_VALUE);  // Smallest value (negative)
 40       printBits (Float.MIN_VALUE);   // Smallest postitive value
 41       printBits (-Float.MIN_VALUE);  // Largest negative value
 42    }
 43 }