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();
}
Advertisements

One thought on “Java: converting a float to a byte array and back again

  1. Pingback: What is the worst programming language? | Richard's Tech Notes

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s