Java Top

I just announced the new Learn Spring course, focused on the fundamentals of Spring 5 and Spring Boot 2:

>> CHECK OUT THE COURSE

1. Overview

In this quick tutorial, we’ll explore a few examples of using Java to convert a float to a byte array and vice versa.

This is simple if we convert an int or a long to a byte array as Java Bitwise Operators works only on integer types. However, for a float, we need to use another layer of conversion.

For instance, we can use APIs provided by the Float class or ByteBuffer class of java.nio package.

2. Float to Byte Array Conversion

As we know, the size of a float in Java is 32 bit which is similar to an int. So we can use floatToIntBits or floatToRawIntBits functions available in the Float class of Java. And then shift the bits to return a byte array. Click here to learn more about bit shifting operations.

The difference between both is floatToRawIntBits preserves Not-a-Number (NaN) values as well. Here shifting the bits has been done through a technique called Narrowing Primitive Conversion.

Firstly let’s have a look of the code with Float class function:

public static byte[] floatToByteArray(float value) {
    int intBits =  Float.floatToIntBits(value);
    return new byte[] {
      (byte) (intBits >> 24), (byte) (intBits >> 16), (byte) (intBits >> 8), (byte) (intBits) };
}

Secondly a neat way of conversion using ByteBuffer:

ByteBuffer.allocate(4).putFloat(value).array();

3. Byte Array to Float Conversion

Let’s now convert a byte array into a float using Float class function intBitsToFloat.

However, we need to first convert a byte array into int bits using the left shift:

public static float byteArrayToFloat(byte[] bytes) {
    int intBits = 
      bytes[0] << 24 | (bytes[1] & 0xFF) << 16 | (bytes[2] & 0xFF) << 8 | (bytes[3] & 0xFF);
    return Float.intBitsToFloat(intBits);  
}

Converting a byte array into a float using ByteBuffer is as simple as this:

ByteBuffer.wrap(bytes).getFloat();

4. Unit Testing

Let’s look at simple unit test cases for implementation:

public void givenAFloat_thenConvertToByteArray() {
    assertArrayEquals(new byte[] { 63, -116, -52, -51}, floatToByteArray(1.1f));
}

@Test
public void givenAByteArray_thenConvertToFloat() {
   assertEquals(1.1f, byteArrayToFloat(new byte[] { 63, -116, -52, -51}), 0);
}

5. Conclusion

We have seen different ways of float to byte conversion and vice-versa.

Float class provides functions as a workaround for such conversion. However, ByteBuffer provides a neat way to do this. For this reason, I suggest using it wherever possible.

The complete source code of these implementations and unit test cases can be found in the GitHub project.

Java bottom

I just announced the new Learn Spring course, focused on the fundamentals of Spring 5 and Spring Boot 2:

>> CHECK OUT THE COURSE