[英]How to convert from a float to 4 bytes in Java?
我一直无法转换这样的东西:
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]
从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);
将字节转换为 int 并使用 Float.intBitsToFloat()
http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/Float.html#intBitsToFloat(int )
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.