Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get byte[] from float number

Tags:

java

math

How to get byte[] from float number? I need to create message where for data I have four bytes, datum can be unsigned int( it is easy to get byte[] from int), binary and float ( but I don't know how to get four bytes from float ). Any solution ?

like image 210
Almira Bojani Avatar asked May 17 '11 07:05

Almira Bojani


2 Answers

You can use Float.floatToRawIntBits(float) but I suspect you don't need byte[] but instead want to be able to write to a stream of bytes. In which case I would use DataOutputStream.writeFloat(float)

If you are using NIO, you can use ByteBuffer.putFloat() An advantage of ByteBuffer is that you can specify a ByteOrder with ByteBuffer.order() so you can handle either Big or Little endian.

like image 68
Peter Lawrey Avatar answered Oct 29 '22 07:10

Peter Lawrey


Class java.lang.Float has methods floatToIntBits() and floatToRawIntBits() which you can use to get at the bit pattern of a float (as an int). So you could do something like this:

float value = 1.5e-3f;

int bits = Float.floatToIntBits(value);
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);

Note: You'd have to find out for your particular application which of floatToIntBits() or floatToRawIntBits() is appropriate and you'd have to determine in which order you need the bytes (little or big endian).

like image 42
Jesper Avatar answered Oct 29 '22 06:10

Jesper