gpt4 book ai didi

java - 如何将字节数组转换为 double 并返回?

转载 作者:IT老高 更新时间:2023-10-28 20:41:47 26 4
gpt4 key购买 nike

为了将字节数组转换为 double ,我发现了这个:

//convert 8 byte array to double
int 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);

但我找不到任何可以将 double 转换为字节数组的东西。

最佳答案

甚至更简单,

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 - 如何将字节数组转换为 double 并返回?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2905556/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com