如何将字节数组转换为数字值(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 更换长,如果你有超过8字节。
Replace long with BigInteger, if you have more than 8 bytes.
感谢阿龙Digulla为我的错误修正。
Thanks to Aaron Digulla for the correction of my errors.
这篇关于如何将字节数组转换为数字值(Java)的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文