Articles, dummyCategory

Convert a Float to a Byte Array in Java | Baeldung

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