1

Does LargeInteger have an equivalent to BigInteger's testBit?

If not, how can testBit be performed on a LargeInteger?

I don't yet have the necessary skills to reproduce ((this & (1<<n)) != 0).


I tried making a method by just copying & pasting the above code referenced from the docs:

static boolean testBit(int n){
    return ((this & (1<<n)) != 0);
}

However, the compiler reports:

error: non-static variable this cannot be referenced from a static context
    return ((this & (1<<n)) != 0);
             ^
error: bad operand types for binary operator '&'
    return ((this & (1<<n)) != 0);
                  ^
Andrew Barber
  • 39,603
  • 20
  • 94
  • 123

1 Answers1

3

This is the best I can come up with given the API:

static boolean testBit(LargeInteger i, int n) {
    return i.shiftRight(n).isOdd();
}

n is the position of the bit to be tested.

I assume you put this method in some utility class.

Explanation

Normally, you would do num & (1 << pos) to extract the bit at pos position:

???????x?????
0000000100000
-------------
0000000x00000

If the whole thing is 0 then x is 0; otherwise, x is 1.


In the method above, I do num >> pos:

???????x?????
-------------
????????????x

We know that a binary number is odd when its least significant bit is 1, and it is even when its least significant bit is 0.

So if the number after right-shifting is odd, we know the bit is 1; if even, we know the bit is 0.

nhahtdh
  • 55,989
  • 15
  • 126
  • 162
  • @Gracchus: It is correct. `i & (1 << n)` leaves only the bit at position `n` on, and `(i >> n) & 1` does the same thing (extract the bit at position `n`). A binary number whose least significant digit is 1 means the number is odd. That explains the part I test for odd number (without AND with 1). – nhahtdh Jan 22 '14 at 16:11
  • @Gracchus: Can you isolate the error? I also want to know why it doesn't work for you. – nhahtdh Jan 24 '14 at 02:50