Java: converting a float to a byte array and back again

Many physical variables are best represented as floats and sometimes it is necessary to pass these variables across a network link. Floats are very standardized and can be safely passed around between different architectures and operating systems but need to be converted to a byte stream first (something like JSON can send floats as strings but this is pretty inefficient in time and space). In C or C++ this is pretty easy but Java is strongly typed and doesn’t make it easy to convert a float value to a byte stream and vice versa. However it can be done…

public void convertFloatToByteArray(float f, byte[] b, int offset) {
   ByteBuffer.wrap(b, offset, 4).order(ByteOrder.LITTLE_ENDIAN).putFloat(f);
}

public float convertByteArrayToFloat(byte[] b, int offset) {
   return ByteBuffer.wrap(b, offset, 4).order(ByteOrder.LITTLE_ENDIAN).getFloat();
}
%d bloggers like this: