Presents your JAVA E-NEWSLETTER for November 20, 2003 <-------------------------------------------> NOTICE TO SUBSCRIBERS: Due to the Thanksgiving holiday, the Java e-newsletter will not be delivered on Nov. 27, 2003. Look for your next edition of Java on Dec. 4, 2003. ---------------------------------------- SAVE TIME WHEN CODING IEEE FLOATING POINT NUMBERS While it's likely that you've heard of IEEE floating point numbers, you've probably never had to deal with them on a bit-by-bit basis. The next time your Java project needs to be able to create floating point numbers from a series of bits or to create a sequence of bits from a floating point number, the Float class does the work for you. A REFRESHER ON IEEE FLOATING POINT NUMBERS The IEEE 754 floating-point single precision number format defines a bit layout for storing floating point numbers. One bit is set aside for the sign, eight bits are set aside for the exponent, and 23 bits are set aside for the mantissa. These bits are laid out in order from the most significant bit to the least significant as illustrated below: 31 0 | | SEEEEEEEEMMMMMMMMMMMMMMMMMMMMMMM where: S = sign bit E = exponent M = mantissa You can purchase a complete explanation of IEEE floating point numbers from IEEE's site. (If you search online for IEEE 754, you should be able to find what you need for free.) FLOAT'S CONTRIBUTION TO THE JAVA COMMUNITY The sample program below uses two of Float's methods to convert a float to bits and those bits back to a float. To convert a float value to a sequence of bits, use Float.floatToIntBits(float f). This method returns a 32-bit integer representing the IEEE 754 arranged bits of the floating point number you supply as an argument. To move in the opposite direction, you use the Float.intBitsToFloat(int bits) method. This method takes the integer passed and unpacks the bits into an IEEE floating point number. Here's the sample program: public class BitsTip { public static void main(String args[]) { float f = Float.parseFloat(args[0]); int bits = Float.floatToIntBits(f); System.out.println("bits: " + bits); System.out.println("back to float: " + Float.intBitsToFloat(bits)); } } If you've ever had to code this conversion by hand, then you'll appreciate the work these two simple methods save you. If you're dealing with 64-bit numbers, then check out the Double wrapper class. It has the same methods for IEEE 754 double precision numbers. Be sure to read the javadoc for any gotchas and to get a complete idea of what these methods can do. David Petersheim is the Director of Application Development with Genscape, Inc. He designs and develops server-side applications to acquire and process real-time energy data. ----------------------------------------