如何将字节数组转换为数字值(Java)的?数组、转换为、字节、如何将

2023-09-10 22:38:41 作者:眼里漫星河

我有一个8字节数组,我想将它转化成其相应的数值。

I have an 8 byte array and I want to convert it to its corresponding numeric value.

例如。

byte[] by = new byte[8];  // the byte array is stored in 'by'

// CONVERSION OPERATION
// return the numeric value

我想将执行上述转换操作的方法。

I want a method that will perform the above conversion operation.

推荐答案

假设第一个字节是最显著字节:

Assuming the first byte is the least significant byte:

long value = 0;
for (int i = 0; i < by.length; i++)
{
   value += ((long) by[i] & 0xffL) << (8 * i);
}

时的第一个字节最显著,那么它是一个有点不同:

Is the first byte the most significant, then it is a little bit different:

long value = 0;
for (int i = 0; i < by.length; i++)
{
   value = (value << 8) + (by[i] & 0xff);
}

与的BigInteger 更换长,如果你有超过8字节。

Replace long with BigInteger, if you have more than 8 bytes.

感谢阿龙Digulla为我的错误修正。

Thanks to Aaron Digulla for the correction of my errors.