BigInteger如何将字节数组转换为Java中的数字?

时间:2016-04-01 12:01:07

标签: java byte biginteger

我有这个小代码:

public static void main(String[] args)  {

    byte[] bytesArray = {7,34};
    BigInteger bytesTointeger= new BigInteger(bytesArray);
    System.out.println(bytesTointeger);

}

输出:1826

我的问题是刚刚发生了如何将字节数组{7,34}转换为此数字1826,导致此结果的操作是什么?比如如何手动转换它

3 个答案:

答案 0 :(得分:11)

数字1826是二进制的,11100100010。 如果将其拆分为8位组,则会得到以下结果:

00000111 00100010

数字7和34

答案 1 :(得分:0)

7和34转换为二进制,并给出00000111和00100010.加入后,它变为11100100010,即1826年的十进制。

答案 2 :(得分:0)

如上所述,这会在big-endian order中的字节表示中创建BigDecimal

如果我们使用long来存储结果,则手动转换可能如下所示:

long bytesToLong(byte[] bs) {
    long res = 0;
    for (byte b : bs) {
        res <<= 8;   // make room for next byte
        res |= b;    // append next byte
    }
    return res;
}

电子。 G:

byte[] bs;    
bs = new byte[]{ 7, 34 };
assertEquals(new BigInteger(bs).longValue(), bytesToLong(bs));  // 1826
bs = new byte[]{ -1 };
assertEquals(new BigInteger(bs).longValue(), bytesToLong(bs));  // -1
相关问题