BigInteger is divided into parts

I want to access some parts of a large whole. In particular, I want to divide a large integer into 4 equal parts. If the bit length is not divisible by 4, I want to add a sufficient number of leading zeros so that the length is 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 lots of extra large integers, as well as a lot of unnecessary shifts and subtractions. Perhaps you can add a test to make sure that it ahas at least 4 bits, but this is not necessary in my case, since I know that this is true before calling the function.

Is there a way to extend the BigInteger class and work directly with the array int[] mag? An extended class should have something similar to the partitionone above, where it returns an array of 4 BigInteger immutable values.

+4
source share
1 answer

I do not quite understand your problem. The desire that I answer makes sense to you :).

In BigIntegerit provides toByteArray(), which returns a byte[]containing a 2-compliment representation of itself BigInteger. At the same time, there is a constructor that accepts byte[].

, , BigInteger . BigInteger , .

+3

All Articles