为什么我会从以下功能中获取垃圾?
传入的_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();
}
答案 0 :(得分:1)
我举了一个小例子来看看如何来回转换。
希望有帮助。
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();
}
}
请注意,如果缓冲区中剩余的字节数少于八个,则ByteBuffer#getDouble()
方法将抛出BufferUnderflowException
。 (请参阅JavaDoc)
答案 1 :(得分:0)
您在代码中使用
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();
答案 2 :(得分:0)
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不一定会更快,当然在需要同步时也不会更快。