Java: Bytes to floats / ints

Note: I recommend @Ophidian's ByteBuffer approach below, it's much cleaner than this. However this answer can be helpful in understanding the bit arithmetic going on.

I don't know the endianness of your data. You basically need to get the bytes into an int type depending on the order of the bytes, e.g.:

int asInt = (bytes[0] & 0xFF) 
            | ((bytes[1] & 0xFF) << 8) 
            | ((bytes[2] & 0xFF) << 16) 
            | ((bytes[3] & 0xFF) << 24);

Then you can transform to a float using this:

float asFloat = Float.intBitsToFloat(asInt);

This is basically what DataInputStream does under the covers, but it assumes your bytes are in a certain order.

Edit - On Bitwise OR

The OP asked for clarification on what bitwise OR does in this case. While this is a larger topic that might be better researched independently, I'll give a quick brief. Or (|) is a bitwise operator whose result is the set of bits by individually or-ing each bit from the two operands.

E.g. (in binary)

   10100000
|  10001100
-----------
   10101100

When I suggest using it above, it involves shifting each byte into a unique position in the int. So if you had the bytes {0x01, 0x02, 0x03, 0x04}, which in binary is {00000001, 00000010, 00000011, 00000100}, you have this:

                                  0000 0001   (1)
                        0000 0010             (2 <<  8)
              0000 0011                       (3 << 16)
  | 0000 0100                                 (4 << 24)
  --------------------------------------------------------
    0000 0100 0000 0011 0000 0010 0000 0001   (67 305 985)

When you OR two numbers together and you know that no two corresponding bits are set in both (as is the case here), bitwise OR is the same as addition.

See Also

  • Wikipedia: Bitwise OR

You probably want to make use of java.nio.ByteBuffer. It has a lot of handy methods for pulling different types out of a byte array and should also handle most issues of endianness for you (including switching the byte order if necessary).

byte[] data = new byte[36]; 
//... populate byte array...

ByteBuffer buffer = ByteBuffer.wrap(data);

int first = buffer.getInt();
float second = buffer.getFloat();

It also has fancy features for converting your byte array to an int array (via an IntBuffer from the asIntBuffer() method) or float array (via a FloatBuffer from the asFloatBuffer() method) if you know that the input is really all of one type.


Use a DataInputStream as follows:

    DataInputStream dis = new DataInputStream(new ByteArrayInputStream(data));
    float f = dis.readFloat();

    //or if it's an int:        
    int i = dis.readInt();