I want to access certain parts of a big integer. In particular, I want to divide the big integer into 4 equal parts. If the bit length is not divisible by 4, I want enough leading zeros added to make the length a multiple of 4. I have the following code that works as described:
public static BigInteger[] partition(BigInteger a) { int base = (a.bitLength()+3)/4; BigInteger upper = a.shiftRight(2*base); BigInteger lower = a.subtract(upper.shiftLeft(2*base)); BigInteger a2 = lower.shiftRight(base); BigInteger a1 = lower.subtract(a2.shiftLeft(base)); BigInteger a4 = upper.shiftRight(base); BigInteger a3 = upper.subtract(a4.shiftLeft(base)); return new BigInteger[] {a1, a2, a3, a4}; } The problem with this code is the overhead of creating many additional big integers as well as many unnecessary shifts and subtracts. Perhaps a test can be added to make sure that a has at least 4 bits, but that is not necessary in my case since I know that to be true before calling the function.
Is there a way to extend the BigInteger class and work with the int[] mag array directly? The extended class should have something similar to partition given above where it returns an array of 4 immutable BigInteger values.