Almira Bojani
Almira Bojani

Reputation: 579

How to get byte[] from float number

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 ?

Upvotes: 5

Views: 10965

Answers (5)

Peter Lawrey
Peter Lawrey

Reputation: 533462

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.

Upvotes: 15

amal
amal

Reputation: 1369

 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);
                    }
            }

Upvotes: 1

Costi Ciudatu
Costi Ciudatu

Reputation: 38195

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.

Upvotes: 3

Jesper
Jesper

Reputation: 206776

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

Upvotes: 9

gustafc
gustafc

Reputation: 28865

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

Upvotes: 1

Related Questions