按位与上对方的非 : public BigInteger andNot(BigInteger val)
按位或 : public BigInteger or(BigInteger val)
按位异或 : public BigInteger xor(BigInteger val)
按位非 : public BigInteger not()
使用示例
1 2 3 4 5 6 7 8 9 10 11 12 13
publicclassTest{ publicstaticvoidmain(String[] args){ BigInteger x = new BigInteger("01011100110", 2); // 二进制构建大整数 BigInteger y = new BigInteger("-1001001", 2);
System.out.printf("x & y = %s\n", x.and(y).toString(2)); System.out.printf("x & !y = %s\n", x.andNot(y).toString(2)); System.out.printf("x | y = %s\n", x.or(y).toString(2)); System.out.printf("x ^ y = %s\n", x.xor(y).toString(2)); System.out.printf("!x = %s\n", x.not().toString(2));
} }
1 2 3 4 5 6
输出结果 : x & y = 1010100110 x & !y = 1000000 x | y = -1001 x ^ y = -1010101111 !x = -1011100111
/** * Returns the number of bits in the minimal two's-complement * representation of this BigInteger, <em>excluding</em> a sign bit. * For positive BigIntegers, this is equivalent to the number of bits in * the ordinary binary representation. For zero this method returns * {@code 0}. (Computes {@code (ceil(log2(this < 0 ? -this : this+1)))}.) * * @return number of bits in the minimal two's-complement * representation of this BigInteger, <em>excluding</em> a sign bit. */ /** * 返回这个BigInteger对应二进制补码形式中除去符号位后的二进制位的个数 * 对于正的大整数, 结果和平凡的二进制形式的长度相同, 对于0直接返回0 */ publicintbitLength(){ int n = bitLengthPlusOne - 1; // 懒惰求值, bitLengthPlusOne初始化为0 // 存放bitLength + 1的值; // 如果n != -1则说明已经求过了, 直接 // 返回n即可。 if (n == -1) { // 没有求值过 int[] m = mag; int len = m.length; if (len == 0) { // 由于mag数组规定是没有前导0的, 所以len == 0就说明这个大整数是0 n = 0; } else { // 计算mag数组二进制形式下的长度, 长度是清除二进制形式下的前导0后的结果 // 计算 : len - 1个int所用的二进制位的个数 + // 最高位int除去二进制下的前导0后的二进制位的个数 // /// 比如设mag = {7, 10} => 0000,0007,0000,000A => 长度 : 32 + 3 = 35 int magBitLength = ((len - 1) << 5) + bitLengthForInt(mag[0]); if (signum < 0) { // 如果是负数则需要判断是否为负的2的幂 // Check if magnitude is a power of two boolean pow2 = (Integer.bitCount(mag[0]) == 1); for (int i=1; i< len && pow2; i++) pow2 = (mag[i] == 0); // 如果是负的2的幂, 则mag数组最高的二进制位的1同时也是符号位, // 所以为了去除符号位后需要将magBitLength减一 n = (pow2 ? magBitLength - 1 : magBitLength); } else { // 对于正的大整数, 结果就是n n = magBitLength; } } bitLengthPlusOne = n + 1; // 缓存结果到bitLengthPlusOne } return n; }