[英]convert byte array to double
为什么我从以下函数中得到了垃圾?
传入的_data
参数是byte[] = {6D, F3, B4, 15}
_endian
参数是ByteOrder.ByteOrder.LITTLE_ENDIAN
ByteBuffer m_ByteBuffer;
public static double ByteToDouble(byte[] _data, int offset, ByteOrder _endian){
synchronized (m_ByteBuffer) {
m_ByteBuffer.clear();
m_ByteBuffer.order(_endian);
m_ByteBuffer.position(0);
m_ByteBuffer.get(_data);
m_ByteBuffer.position(0);
}
return m_ByteBuffer.getDouble();
}
我做了一个小例子来看看如何来回转换。
希望能帮助到你。
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
public class ByteToDouble {
public static void main(String[] args) throws IOException {
double d1 = 123.456;
double d2 = bytesToDouble(doubleToBytes(d1));
System.out.printf("d1: %f\nd2: %f\n", d1, d2);
}
public static byte[] doubleToBytes(double d) throws IOException {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
DataOutputStream dos = new DataOutputStream(bos);
dos.writeDouble(d);
dos.flush();
return bos.toByteArray();
}
public static double bytesToDouble(byte[] bytes) {
ByteBuffer buffer = ByteBuffer.wrap(bytes).order(ByteOrder.BIG_ENDIAN);
return buffer.getDouble();
}
}
请注意,如果缓冲区中剩余的字节少于 8 个,则ByteBuffer#getDouble()
方法将抛出BufferUnderflowException
。 (见 JavaDoc)
在您使用的代码中
m_ByteBuffer.get(_data);
这会将缓冲区的数据读入_data
。 我想你想使用的是ByteBuffer#put
m_ByteBuffer.put(_data);
此外,在将数据放入缓冲区后,更常用的是使用flip而不是position(0)
因为这正确设置了缓冲区的限制。 总而言之,这将大致导致:
m_ByteBuffer.order(_endian);
m_ByteBuffer.clear();
m_ByteBuffer.put(_data);
m_ByteBuffer.flip();
m_ByteBuffer.getDouble();
4 个字节表示一个float
,8 个字节表示一个double
。
byte[] data = {0x6D, 0xF3, 0xB4, 0x15};
double x = bytesToDouble(data);
public static double bytesToDouble(byte[] data) {
ByteBuffer bb = ByteBuffer.wrap(data).order(ByteOrder.LITTLE_ENDIAN);
return data.length == 4 ? bb.getFloat() : bb.getDouble();
}
ByteBuffer.wrap(byte[])
是一个轻量级的数组包装,具有写入字节的能力。 全局 ByteBuffer 不一定更快,当然在需要同步时更是如此。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.