Search code examples
bit-manipulationbit

Clear i to 0 bits


I'm working through Cracking the Coding Interview and one of the bit manipulations techniques is as follows:

To clear all bits from i through 0 (inclusive), we take a sequence of all 1s (which is -1) and shift it left by i + 1 bits. This gives us a sequence of 1s (in the most significant bits) followed by i 0 bits.

int clearBitsIthrough0(int num, int i){
    int mask = (-1 << (i + 1));
    return num & mask;
}

How is -1 a sequence of all 1s?


Solution

  • Assuming you are using C/C++, int represents a signed 32-bit integer represented with two's complement.

    -1 by itself is assumed to be of type int, and therefore is equivalent to 0xFFFFFFFF. This is derived as follows:

    1 is 0x00000001. Inverting the bits gives 0xFFFFFFFE, and adding one yields the two's complement representation of -1: 0xFFFFFFFF, a sequence of 32 ones.