Noam Nevo
Noam Nevo

Reputation: 3081

Java bitwise operation Vs BigInteger

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);

Upvotes: 9

Views: 8984

Answers (1)

Evgeniy Dorofeev
Evgeniy Dorofeev

Reputation: 136002

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);

Upvotes: 13

Related Questions