我正在尝试将字节数组转换为 double 值。
private static double bytesToDouble(byte[] array) {
long l=bytesToLong(array[7],array[6],array[5],array[4],array[3],array[2],array[1],array[0]);
return Double.longBitsToDouble(l);
}
private static long bytesToLong(byte b7,byte b6,byte b5,byte b4,byte b3,byte b2,byte b1,byte b0){
//se il byte è signed viene trasf. in unsigned
return (b0<0 ? b0+256L : b0) |
((b1<0 ? b1+256L : b1) << 8) |
((b2<0 ? b2+256L : b2) << 16)|
((b3<0 ? b3+256L : b3) << 24)|
((b4<0 ? b4+256L : b4) << 32)|
((b5<0 ? b5+256L : b5) << 40)|
((b6<0 ? b6+256L : b6) << 48)|
((b7<0 ? b7+256L : b7) << 56);
}
无论如何,有些东西似乎无法正常工作。我知道输入数组是
0 0 0 0 0 0 12 -124
预期值为 641.5,但我得到另一个值 (-3.591469701136079E-289)。
我知道生成字节序列的代码运行良好,因为它已经在生产环境中使用了很长时间。
如何操作字节数组(或字节本身)以获得预期值?
问候
最佳答案
byte[] bytes = new byte[8];
ByteBuffer.wrap(bytes).putDouble(641.5);
System.out.println("Result: " + Arrays.toString(bytes));
// Result: [64, -124, 12, 0, 0, 0, 0, 0]
因此字节顺序是小端(Windows Intel),尤其是一个字节值丢失,一个 read()
太多;我猜这是一个愚蠢的错误,例如:
while (read() != -1) {
... read array
正确的数据可以通过以下方式转换:
double val = ByteBuffer.wrap(array).order(ByteOrder.LITTLE_ENDIAN).getDouble();
关于Java字节数组到 double 转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42295580/