Java byte array to double 转换
Java byte array to double conversion
我正在尝试将字节数组转换为双精度值。
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)。
我知道生成字节序列的代码效果很好,因为它在生产环境中使用了很长时间。
如何操作字节数组(或字节本身)以获得预期值?
此致
尝试使用 java.nio.ByteBuffer (https://docs.oracle.com/javase/7/docs/api/java/nio/ByteBuffer.html)
例如,
double val = ByteBuffer.wrap(array).getDouble(0);
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 英特尔),尤其是一个字节值丢失了,一个 read()
太多了;我猜这是一个愚蠢的错误,例如:
while (read() != -1) {
... read array
正确的数据可以转换为:
double val = ByteBuffer.wrap(array).order(ByteOrder.LITTLE_ENDIAN).getDouble();
我正在尝试将字节数组转换为双精度值。
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)。
我知道生成字节序列的代码效果很好,因为它在生产环境中使用了很长时间。
如何操作字节数组(或字节本身)以获得预期值?
此致
尝试使用 java.nio.ByteBuffer (https://docs.oracle.com/javase/7/docs/api/java/nio/ByteBuffer.html)
例如,
double val = ByteBuffer.wrap(array).getDouble(0);
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 英特尔),尤其是一个字节值丢失了,一个 read()
太多了;我猜这是一个愚蠢的错误,例如:
while (read() != -1) {
... read array
正确的数据可以转换为:
double val = ByteBuffer.wrap(array).order(ByteOrder.LITTLE_ENDIAN).getDouble();