How does BigInteger convert an array of bytes to a number in Java?

I have this little code:

public static void main(String[] args)  {

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

}

Output: 1826

My question is what happened, how the byte array {7.34} was converted to that number 1826, what is the operation that caused this result? for example, how to convert it manually

+4
source share
3 answers

The number 1826 is in binary format 11100100010. If you divide it into groups of 8 bits, you get the following:

00000111 00100010

What are the numbers 7 and 34

+11
source

7 and 34 are converted to binary and give 00000111 and 00100010. After combining, it becomes 11100100010, which is in decimal 1826.

0
source

, BigDecimal big-endian.

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;
}

. :.

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
0
source

All Articles