0

I have a long and I want to check if a bit at particular position is set or not.

Suppose the long A

0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0001 0010 0100 0100

So the bit at 3, 7, 10, 13 positions are set.

Now I have another long B

0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0010 0000 0000

and in this long 10 position bit is set. ( It is guaranteed that only one bit will be set in second long )

Now by comparing above two longs A and B I want to determine if the 10 position bit is set in A long or not.

One solution is

  1. I first check in B long which position bit is set lets say this position is p. This involves looping over each bit to check if that bit is set.

  2. Now in A long I can check if p bit is set or not

My question is there any other solution, because I don't want to loop over each bit and I don't know the position of which bit to check beforehand.

EDIT: I had a look at Java: Checking if a bit is 0 or 1 in a long and in this question x is known beforehand but I don't know the position beforehand.

Community
  • 1
  • 1
Ritesh
  • 113
  • 8

2 Answers2

1

To check if a certain bit is set, use the & operator with the mask that represents this bit.

For example:

    long vectorValue = 985739487549L;
    long bitMask = 32L;

    boolean hasBit = false;
    int vectorMaskedValue = vectorValue & bitMask;
    if (vectorMaskedValue == bitMask)
    {
        hasbit = true;
    }
Yoav Gur
  • 1,366
  • 9
  • 15
1

If you want to know if the (only) 1 bit of B is also set in A you simply need to bit-wise AND the two :

if (A & B != 0) {

}

Since B has only a single 1 bit, A & B will be non-zero if and only if the same bit is 1 in A.

Eran
  • 387,369
  • 54
  • 702
  • 768