My numbers are base 256 from left to right and represented in byte array. I would like to convert them to BigInteger such that below examples will work:
- [5] -> 5
- [200] -> 200
- [0,1] -> 256
- [100,2] -> 612
I came up with this solution:
byte[] input = new byte[]{(byte) 200,2};
BigInteger a = BigInteger.ZERO;
BigInteger base = BigInteger.valueOf(256);
for (int i = 0; i < input.length; i++) {
a = a.add(BigInteger.valueOf(input[i] & 0xFF).multiply(base.pow(i)));
}
System.out.println(a);
While it works, it feels very inefficient. Is there a more efficient way of doing this?
new BigInteger(array). That'd be much most efficient than what you're currently doing.