如何将字节数组转换为其数值(Java)? [英] How to convert a byte array to its numeric value (Java)?
本文介绍了如何将字节数组转换为其数值(Java)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个 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 替换 long,如果你有超过 8 个字节.
Replace long with BigInteger, if you have more than 8 bytes.
感谢 Aaron Digulla 纠正我的错误.
Thanks to Aaron Digulla for the correction of my errors.
这篇关于如何将字节数组转换为其数值(Java)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文