Java按位运算与BigInteger

Noa*_*evo 7 java bit-manipulation

在性能方面使用纯按位运算(& | ^ ~)而不是使用BigInteger(BigInteger.and BigInteger.or)进行按位运算是否有优势?记忆?还要别的吗?

因为我使用BigInteger进行按位运算,因为生成的代码更加可读.

我将使用的代码示例:

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);
Run Code Online (Sandbox Code Playgroud)

Evg*_*eev 9

在性能和内存方面使用原语总是更有效.但BigInteger可以处理大于int和long的数字.例如

BigInteger b1 = new BigInteger("1111111111111111111111111111111111111111111111111");
BigInteger b2 = new BigInteger("2222222222222222222222222222222222222222222222222");
BigInteger b3 = b1.and(b2);
Run Code Online (Sandbox Code Playgroud)

  • 我认为 Noam 要求的是一个用例,而不是如何实现它。处理 IPv6 地址(128 位)的子网掩码就是其中之一。 (3认同)