How to get byte [] from a floating point number

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

+4
source share
5 answers

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

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

+14
source

The java.lang.Float class has methods floatToIntBits() and floatToRawIntBits() , which you can use to get the float bitmap (as an int ). So you can 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 will need to find for your specific application which of floatToIntBits() or floatToRawIntBits() is suitable, and you will need to determine in which order you need bytes (small or large end).

+9
source

Without any math, you can do this by writing a value through a DataOutputStream , and then extract the result:

 ByteArrayOutputStream bos = new ByteArrayOutputStream(4); DataOutputStream dos = new DataOutputStream(bos); dos.writeFloat(yourFloat); byte[] bytes = bos.toByteArray(); // at this point, your bytes will contain the 4-byte representation of the float. 
+3
source

If you find it easy to get int bytes, Float.floatToIntBits , probably you want:

 float f = ...; int i = Float.floatToIntBits(f); byte[] floatBytes = toBytes(i); 
+1
source
  public static void main(String[] args) { float f = 23f; byte[] op = new byte[4]; int fi = Float.floatToIntBits(f); for (int i = 0; i < 4; i++) { int offset = (op.length - 1 - i) * 8; op[i] = (byte) ((fi >>> offset) & 0xff); } for(byte b : op) { System.out.format("0x%02X ", b); } } 
+1
source

All Articles