bit-manipulationbitwise-operatorsbitand-operator

Why is INT_MAX & x = x?


While doing the question ANDROUND on spoj, I wanted to write the query function for my segment tree. There in the situation when l, r are out of range i need to return a number which while doing the BITWISE AND operation, would not change the answer.

In one of the solutions, I observed that bitwise AND of any number with INT_MAX will return us the number itself.

Why is this so?


Solution

  • Because INT_MAX is a number that is represented only by 1's. for 32-bit int, it is represented by the bit sequence 11111111 11111111 11111111 11111111. Now, the & operator, checks if both numbers have a value of 1 at some index (For example, if both numbers have a value of 1 at index 5, the result will have a value of 1 at index 5). If that is the case, the result will have a value of 1 in that index, otherwise, it will store a value of 0 in that index of the result.

    So if you consider the INT MAX number - which again, is the bit sequence 11111111 11111111 11111111 11111111 and the number 2, for example, which is represented by the bit sequence 00000000 00000000 00000000 00000010. Only in the 2nd smallest index, there is a 1 in both numbers so only there the result will have 1, and 0 everywhere else.

    Horizontal visualization

    11111111 11111111 11111111 11111111

    &

    00000000 00000000 00000000 00000010

    =

    00000000 00000000 00000000 00000010