Java 如何将字节数组转换为双精度并返回?
为了将字节数组转换为双精度型,我发现了这一点:
//convert 8 byte array to doubleint start=0;//???
int i = 0;
int len = 8;
int cnt = 0;
byte[] tmp = new byte[len];
for (i = start; i < (start + len); i++) {
tmp[cnt] = arr[i];
//System.out.println(java.lang.Byte.toString(arr[i]) + " " + i);
cnt++;
}
long accum = 0;
i = 0;
for ( int shiftBy = 0; shiftBy < 64; shiftBy += 8 ) {
accum |= ( (long)( tmp[i] & 0xff ) ) << shiftBy;
i++;
}
return Double.longBitsToDouble(accum);
但是我找不到将双精度型转换为字节数组的任何东西。
回答:
甚至更简单
import java.nio.ByteBuffer;public static byte[] toByteArray(double value) {
byte[] bytes = new byte[8];
ByteBuffer.wrap(bytes).putDouble(value);
return bytes;
}
public static double toDouble(byte[] bytes) {
return ByteBuffer.wrap(bytes).getDouble();
}
以上是 Java 如何将字节数组转换为双精度并返回? 的全部内容, 来源链接: utcz.com/qa/418881.html