Binary Logic Operations on BigInteger
suggest changeBigInteger supports the bitwise operations that primitive integer types support. As with its arithmetic methods, each operation returns a new BigInteger; it does not change the receiver. not is not a fixed-width invert: not(n) is -n - 1.
Binary Or:
BigInteger val1 = new BigInteger("10");
BigInteger val2 = new BigInteger("9");
System.out.println(val1.or(val2));
Output: 11 (which is equivalent to 10 | 9)
Binary And:
BigInteger val1 = new BigInteger("10");
BigInteger val2 = new BigInteger("9");
System.out.println(val1.and(val2));
Output: 8 (which is equivalent to 10 & 9)
Binary Xor:
BigInteger val1 = new BigInteger("10");
BigInteger val2 = new BigInteger("9");
System.out.println(val1.xor(val2));
Output: 3 (which is equivalent to 10 ^ 9)
RightShift:
BigInteger val1 = new BigInteger("10");
System.out.println(val1.shiftRight(1)); // the argument is an int
Output: 5 (equivalent to 10 >> 1)
LeftShift:
BigInteger val1 = new BigInteger("10");
System.out.println(val1.shiftLeft(1)); // the argument is an int
Output: 20 (equivalent to 10 << 1)
Binary Inversion (Not) :
BigInteger val1 = new BigInteger("10");
System.out.println(val1.not());
Output: -11
NAND (And-Not):*
BigInteger val1 = new BigInteger("10");
BigInteger val2 = new BigInteger("9");
System.out.println(val1.andNot(val2));
Output: 2
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents