I am trying to convert a float
into a primitive byte[]
and vice versa:
public byte[] floatToByteArray(final float value)
{
return new byte[]
{
(byte) (value >> 56),
(byte) (value >> 48),
(byte) (value >> 40),
(byte) (value >> 32),
(byte) (value >> 24),
(byte) (value >> 16),
(byte) (value >> 8),
(byte) (value)
};
}
Oddly enough, when I try to shift the newly allocated byte[]
back into a float
, the result is nothing but rubbish.
However, it would appear as if the same algorithm works just fine when I use the primitive long
data type as argument instead.
public byte[] longToByteArray(final long value)
{
return new byte[]
{
(byte) (value >> 56),
(byte) (value >> 48),
(byte) (value >> 40),
(byte) (value >> 32),
(byte) (value >> 24),
(byte) (value >> 16),
(byte) (value >> 8),
(byte) (value)
};
}
Use these instead.
public static byte [] long2ByteArray (long value)
{
return ByteBuffer.allocate(8).putLong(value).array();
}
public static byte [] float2ByteArray (float value)
{
return ByteBuffer.allocate(4).putFloat(value).array();
}
Just to add another useful one based on @shazin solution. Convert a float array into a byte array:
public static byte[] FloatArray2ByteArray(float[] values){
ByteBuffer buffer = ByteBuffer.allocate(4 * values.length);
for (float value : values){
buffer.putFloat(value);
}
return buffer.array();
}
It wont work. Float.byteValue just truncates float value to 1 byte
public byte byteValue() {
return (byte)value;
}
Besides, it's not clear what bytes you want. Is it IEEE 754 floating-point single-float bit layout? Then you can first convert it to int
int i = Float.floatToIntBits(1.1f); // see Float API, there are actually 2 options
then use shifts to break it into 4 bytes or 8 bytes like you did
Also based on Shazin solution, with additional specification on byte order:
ByteBuffer.allocate(4).order(ByteOrder.LITTLE_ENDIAN).putFloat(value).array();
or
ByteBuffer.allocate(4).order(ByteOrder.BIG_ENDIAN).putFloat(value).array();
I cant see easy-to-use methods. It works:
public static byte[] toByteArray(float value) {
byte[] bytes = new byte[4];
ByteBuffer.wrap(bytes).putFloat(value);
return bytes;
}
public static float toFloat(byte[] bytes) {
return ByteBuffer.wrap(bytes).getFloat();
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.