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 ?
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.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With