How to get byte[] from float number

10,239

Solution 1

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.

Solution 2

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).

Solution 3

Without any math involved, you can do that by writing the value via a DataOutputStream and then fetch the resulting output:

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.

Solution 4

If you think it's easy getting the bytes of an int, Float.floatToIntBits is probably what you want:

float f = ...;
int i = Float.floatToIntBits(f);
byte[] floatBytes = toBytes(i);

Solution 5

 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);
                    }
            }
Share:
10,239
Almira Bojani
Author by

Almira Bojani

Updated on June 27, 2022

Comments

  • Almira Bojani
    Almira Bojani almost 2 years

    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 ?

  • funkybro
    funkybro almost 13 years
    +1, this is the best solution for writing floats over a data connection.