[英]How to store float in a Byte array by shifting bits
I can store a int value in a byte array of size 4 using: 我可以使用以下方式将int值存储在大小为4的字节数组中:
byte[] toByteArray(int value) {
return new byte[] {
(byte) (value >> 24),
(byte) (value >> 16),
(byte) (value >> 8),
(byte) value};
}
How can i store a float in a byte array using bit shift? 如何使用移位将浮点数存储在字节数组中?
You should use: Float.floatToIntBits(float val)
to get the raw representation of the float and then convert the returned int
to byte[]
. 您应该使用:
Float.floatToIntBits(float val)
获取Float.floatToIntBits(float val)
的原始表示,然后将返回的int
转换为byte[]
。
To read back the float, use Float.intBitsToFloat(int i)
要读回浮动,请使用
Float.intBitsToFloat(int i)
Remember that a float
is 4 bytes . 请记住,
float
是4个字节 。 You can use a ByteBuffer
to store the float
and provide the byte array for you. 您可以使用
ByteBuffer
来存储float
并为您提供字节数组。
public byte[] toByteArray(float value) {
ByteBuffer buffer = ByteBuffer.allocate(4);
buffer.putFloat(value);
return buffer.array();
}
Internally this uses the Bits
class which does something similar to what you were doing with your toByteArray(int)
method. 在内部,它使用
Bits
类,该类的行为类似于您对toByteArray(int)
方法所做的事情。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.