Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shifting BigInteger of Java by long variable

I know there are methods shiftLeft(int n) and shiftRight(int n) for BigInteger class which only takes int type as an argument but I have to shift it by a long variable. Is there any method to do it?

like image 210
Mani Sankar Avatar asked Dec 25 '22 14:12

Mani Sankar


2 Answers

BigInteger can only have Integer.MAX_VALUE bits. Shifting right by more than this will always be zero. Shift left any value but zero will be an overflow.

From the Javadoc

 * BigInteger constructors and operations throw {@code ArithmeticException} when
 * the result is out of the supported range of
 * -2<sup>{@code Integer.MAX_VALUE}</sup> (exclusive) to
 * +2<sup>{@code Integer.MAX_VALUE}</sup> (exclusive).

If you need more than 2 billion bits to represent your value, you have a fairly usual problem, BigInteger wasn't designed for.

If you need to do bit manipulation on a very large scale, I suggest having an BitSet[] This will allow up to 2 bn of 2 bn bit sets, more than your addressable memory.

yes the long variable might go up to 10^10

For each 10^10 bit number you need 1.25 TB of memory. For this size of data, you may need to store it off heap, we have a library which persist this much data in a single memory mapping without using much heap, but you need to have this much space free on a single disk at least. https://github.com/OpenHFT/Chronicle-Bytes

like image 108
Peter Lawrey Avatar answered Dec 27 '22 04:12

Peter Lawrey


BigInteger does not support values where long shift amounts would be appropriate. I tried

BigInteger a = BigInteger.valueOf(2).pow(Integer.MAX_VALUE);

and I got the following exception:

Exception in thread "main" java.lang.ArithmeticException: BigInteger would overflow supported range.

like image 30
Paul Boddington Avatar answered Dec 27 '22 04:12

Paul Boddington