我无法将像这样的东西转换:
byte[] b = new byte[] { 12, 24, 19, 17};
变成像这样:
float myfloatvalue = ?;
请问能否给我一个例子?
另外,如何将这个浮点数转换回字节?
我无法将像这样的东西转换:
byte[] b = new byte[] { 12, 24, 19, 17};
变成像这样:
float myfloatvalue = ?;
请问能否给我一个例子?
另外,如何将这个浮点数转换回字节?
byte[]
-> float
使用ByteBuffer
:
byte[] b = new byte[]{12, 24, 19, 17};
float f = ByteBuffer.wrap(b).getFloat();
float
-> byte[]
反向操作(已知上述结果):
float f = 1.1715392E-31f;
byte[] b = ByteBuffer.allocate(4).putFloat(f).array(); //[12, 24, 19, 17]
ByteBuffer
的文档,并查看我的更新。 - Tomasz Nurkiewicz.order(ByteBuffer.LITTLE_ENDIAN)
来设置字节顺序。 - Peter LawreyByteBuffer
一起使用。非常感谢! - Atul从 byte[]
转换为 float
,可以这样做:
byte[] b = new byte[] { 12, 24, 19, 17};
float myfloatvalue = ByteBuffer.wrap(b).getFloat();
这里有一种将 float
转换为 byte[]
的替代方法,而不使用 ByteBuffer.allocate
:
int bits = Float.floatToIntBits(myFloat);
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);