Search code examples
bitmasking

Shifting and Masking Binary Bits


I've came across this snippet of code on a book:

    public static short countBits(int x) {
        short numBit =  0;
        while(x != 0) {
            numBit +=  (x&1);
            x >>>= 1;
        }
        return numBit;
    }

However, I'm not really sure how numBit += (x&1); and x >>>= 1 works.
I think that numBit += (x&1) is comparing AND for a single digit and 1. Does it mean that if my binary number is 10001, the function is ANDing the 1000"1" bit with 1 on the first iteration of the while loop? Also, what's the point of >>>= 1 ? I think that ">>>" is shifting the bits to the right by three but I can't figure out the purpose of doing so in this function.

Any help would be much appreciated. Thank you!


Solution

  • This function counts the number of bits that are set to "1". x & 1 is a bitwise-AND with the least significant bit of x's current value (either 1 if x is odd, or 0 if it's even). As such it makes perfect sense to add it to result. x >>>= 1 is equivalent to x = x >> 1 and this means "shift bits in x by 1 position to the right" (or, for unsigned integers, divide x by 2).