Even though you may know about IEEE floating point numbers, you've probably never dealt with them on a bit-by-bit basis. I'll show you how, the next time your Java project needs to create floating point numbers from a series of bits or create a sequence of bits from a floating point number, the Float class can do 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.

Delivered each Thursday, our free Java newsletter provides insight and hands-on tips you need to unlock the full potential of this programming language. Automatically sign up today!