开发者

Java BigInteger(byte[] val)

I am trying to understand how does the java.math.BigInteger.BigInteger(byte[] val) constructor work.

For example when I create a BigInteger instance from the byte array [1, 0], the corresponding string it creates is 256. Surely, the binary string 10 corresponds to value 2 in base 10. Ho开发者_Go百科w does it convert it from 10 to 256? What am I missing?


Each byte in the array represents 8 bits, so [1, 0] is equivalent to 1 * 2^(8 * 1) + 0 * 2^(8 * 0), or, in binary: 00000001 00000000.

Beware that the BigInteger (byte[]) constructor also uses two's complement, so it's not just a matter of adding the unsigned numbers: the most significant bit will affect the sign.


It's effectively working in base-256, not base-2. So each position in the input array is worth 256 times more than the next position.

Pseudo-code:

x = 0;
for (i = 0; i < val.length - 1; i++) {
    x = (x*256) + val[i];
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜