我还没有能够转换这样的东西:
byte[] b = new byte[] { 12, 24, 19, 17};
变成这样:
float myfloatvalue = ?;
谁能给我举个例子?
还如何将浮点数转回字节?
byte[]
-> float
With 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]
从byte[]
-> float
,您可以这样做:
byte[] b = new byte[] { 12, 24, 19, 17};
float myfloatvalue = ByteBuffer.wrap(b).getFloat();
这里是使用ByteBuffer.allocate
转换float
-> byte[]
的替代方法:
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);
将字节转换为整型并使用float . intbitstoffloat ()
http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/Float.html intBitsToFloat (int)