5

I have this small 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 just happened how an array of bytes {7,34} converted into this number 1826 , what is the operation that caused this result ? like how to convert it manually

0

3 Answers 3

11

The number 1826 is, in binary, 11100100010. If you split that in groups of 8 bits, you get the following:

00000111 00100010

Which are the numbers 7 and 34

Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

0

As said, this creates a BigDecimal from its byte representation in big-endian order.

If we used long to store result, manual conversion may look like the following:

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

E. 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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.