Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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);
like image 742
Noam Nevo Avatar asked Apr 30 '13 08:04

Noam Nevo


People also ask

Is Bitwise and faster than modulo?

The result was consistent with the idea that bitwise is faster than modulo operator.

What is BigInteger in Java?

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.

How do I return BigInteger in Java?

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.

How many bytes is BigInteger Java?

That's a total of 20 bytes + the integer array.


1 Answers

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);
like image 83
Evgeniy Dorofeev Avatar answered Oct 08 '22 19:10

Evgeniy Dorofeev