Is there an advantage of using pure bitwise operations (& | ^ ~
) over using BigInteger (BigInteger.and BigInteger.or
) for bitwise operations in terms of performance? memory? anything else?
For i use BigInteger for bitwise operations because the resulting code is much more readble.
example for the code that i will be using:
BigInteger bNum1 = new BigInteger("0");
BigInteger bNum2 = new BigInteger("0");
BigInteger bNum3 = new BigInteger("0");
bNum1 = bNum1.setBit(0);
bNum2 = bNum2.setBit(1);
bNum3 = bNum3.setBit(2);
BigInteger bMask = bNum3.or(bNum1);
System.out.println(bMask.and(bNum1).equals(bMask));
System.out.println(bMask.and(bNum2).equals(bMask));
System.out.println(bMask.and(bNum3).equals(bMask));
System.out.println(bMask.and(bMask).equals(bMask));
int num1 = 1 << 0;
int num2 = 1 << 1;
int num3 = 1 << 2;
int mask = num3 | num1;
System.out.println((mask & num1) == mask);
System.out.println((mask & num2) == mask);
System.out.println((mask & num3) == mask);
System.out.println((mask & mask) == mask);
The result was consistent with the idea that bitwise is faster than modulo operator.
BigInteger provides analogues to all of Java's primitive integer operators, and all relevant methods from java. lang. Math. Additionally, BigInteger provides operations for modular arithmetic, GCD calculation, primality testing, prime generation, bit manipulation, and a few other miscellaneous operations.
and(BigInteger val) method returns a BigInteger whose value is bitwise-AND of two BigIntegers. This method returns a negative number if both of the BigIntegers are negative. The and() method applies bitwise-AND operation upon the current bigInteger and bigInteger passed as parameter.
That's a total of 20 bytes + the integer array.
It is always more efficient to work with primitives both in terms of performance and memory. But BigInteger can work with numbers bigger than int and long. Eg
BigInteger b1 = new BigInteger("1111111111111111111111111111111111111111111111111");
BigInteger b2 = new BigInteger("2222222222222222222222222222222222222222222222222");
BigInteger b3 = b1.and(b2);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With