如何在 Java 中从浮点数转换为 4 个字节?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14308746/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 15:50:01  来源:igfitidea点击:

How to convert from a float to 4 bytes in Java?

javabyteconverter

提问by user1395152

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?

还有如何将浮点数转回字节?

回答by Tomasz Nurkiewicz

byte[]-> float

byte[]-> float

With ByteBuffer:

ByteBuffer

byte[] b = new byte[]{12, 24, 19, 17};
float f =  ByteBuffer.wrap(b).getFloat();

float-> byte[]

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]

回答by Reimeus

From byte[]-> float, you could do:

byte[]-> float,你可以这样做:

byte[] b = new byte[] { 12, 24, 19, 17};
float myfloatvalue = ByteBuffer.wrap(b).getFloat();

Here is an alternative to using ByteBuffer.allocatefor converting float-> byte[]:

这是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);

回答by Chris

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)