I have not been able to convert something like this:
我还没能转化成这样的东西:
byte[] b = new byte[] { 12, 24, 19, 17};
into something like this:
是这样的:
float myfloatvalue = ?;
Could someone please give me an example?
谁能给我举个例子吗?
Also how to turn that float back to bytes?
还有,如何将浮动转换回字节?
3 个解决方案
#1
16
From byte[]
-> float
, you could do:
从byte[] ->浮动,你可以做:
byte[] b = new byte[] { 12, 24, 19, 17};
float myfloatvalue = ByteBuffer.wrap(b).getFloat();
Here is an alternative to using ByteBuffer.allocate
for converting float
-> byte[]
:
这里是使用ByteBuffer的一种替代方法。用于转换float ->字节的分配[]:
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);
#2
36
byte[]
-> float
With ByteBuffer
:
ByteBuffer:
byte[] b = new byte[]{12, 24, 19, 17};
float f = ByteBuffer.wrap(b).getFloat();
float
-> byte[]
Reverse operation (knowing the result of above):
反向操作(知道以上结果):
float f = 1.1715392E-31f;
byte[] b = ByteBuffer.allocate(4).putFloat(f).array(); //[12, 24, 19, 17]
#3
1
Convert the bytes to an int and use Float.intBitsToFloat()
将字节转换为int并使用Float.intBitsToFloat()
http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/Float.html#intBitsToFloat(int)
http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/Float.html intBitsToFloat(int)
#1
16
From byte[]
-> float
, you could do:
从byte[] ->浮动,你可以做:
byte[] b = new byte[] { 12, 24, 19, 17};
float myfloatvalue = ByteBuffer.wrap(b).getFloat();
Here is an alternative to using ByteBuffer.allocate
for converting float
-> byte[]
:
这里是使用ByteBuffer的一种替代方法。用于转换float ->字节的分配[]:
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);
#2
36
byte[]
-> float
With ByteBuffer
:
ByteBuffer:
byte[] b = new byte[]{12, 24, 19, 17};
float f = ByteBuffer.wrap(b).getFloat();
float
-> byte[]
Reverse operation (knowing the result of above):
反向操作(知道以上结果):
float f = 1.1715392E-31f;
byte[] b = ByteBuffer.allocate(4).putFloat(f).array(); //[12, 24, 19, 17]
#3
1
Convert the bytes to an int and use Float.intBitsToFloat()
将字节转换为int并使用Float.intBitsToFloat()
http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/Float.html#intBitsToFloat(int)
http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/Float.html intBitsToFloat(int)