Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 804
user1395152 Avatar asked Jan 13 '13 22:01

user1395152


2 Answers

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]
like image 122
Tomasz Nurkiewicz Avatar answered Sep 20 '22 14:09

Tomasz Nurkiewicz


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);
like image 33
Reimeus Avatar answered Sep 18 '22 14:09

Reimeus