How to convert from a float to 4 bytes in Java?

17,704

Solution 1

From byte[] -> float, you could do:

byte[] b = new byte[] { 12, 24, 19, 17};
float myfloatvalue = ByteBuffer.wrap(b).getFloat();

Here is an alternative to using ByteBuffer.allocate for converting float -> byte[]:

int bits = Float.floatToIntBits(myFloat);
byte[] bytes = new byte[4];
bytes[0] = (byte)(bits & 0xff);
bytes[1] = (byte)((bits >> 8) & 0xff);
bytes[2] = (byte)((bits >> 16) & 0xff);
bytes[3] = (byte)((bits >> 24) & 0xff);

Solution 2

byte[] -> float

With ByteBuffer:

byte[] b = new byte[]{12, 24, 19, 17};
float f =  ByteBuffer.wrap(b).getFloat();

float -> byte[]

Reverse operation (knowing the result of above):

float f =  1.1715392E-31f;
byte[] b = ByteBuffer.allocate(4).putFloat(f).array();  //[12, 24, 19, 17]

Solution 3

Convert the bytes to an int and use Float.intBitsToFloat()

http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/Float.html#intBitsToFloat(int)

Share:
17,704
user1395152
Author by

user1395152

Updated on June 03, 2022

Comments

  • user1395152
    user1395152 about 2 years

    I have not been able to convert something like this:

    byte[] b = new byte[] { 12, 24, 19, 17};
    

    into something like this:

    float myfloatvalue = ?;
    

    Could someone please give me an example?

    Also how to turn that float back to bytes?

  • user1395152
    user1395152 over 11 years
    That helps and what about turning that float back into bytes
  • Bohemian
    Bohemian over 11 years
    +1 honestly, ByteBuffer is an under-used, and under-appreciated class.
  • Tomasz Nurkiewicz
    Tomasz Nurkiewicz over 11 years
    @user1395152: please, read the documentation of ByteBuffer. And see my update.
  • Vishy
    Vishy over 11 years
    +1 You may need to set the byte order with .order(ByteBuffer.LITTE_ENDIAN) as well.
  • Sam
    Sam over 8 years
    Minor point, ByeBuffer encodes in big endian and the current example is in little endian. Making them match would be great! Ty!
  • Atul
    Atul over 7 years
    This helped me a lot. Came handy when needed. Beauty is that it works even with ByteBuffer of Google's protobuf. Many many thanks!