Search code examples
bit-manipulation

0 < res <= (1 << 31) -1 - What does this mean?


This statement checks whether a number is 32 bits.

0 < res <= (1 << 31) -1

I can't seem to understand how, can someone help understand this bit shift syntax?


Solution

  • Well, lets begin with an example:

    1 in binary is 1

    2 in binary is 10

    4 in binary is 100

    We can see that we need to 'add' a 0 at the end of each number to multiply it by 2 and in most languages we can do this with the following syntax: number << 1 Here we are saying that we add a 1 time a 0 to the left. number >> 1 and here we add 1 time a 0 to the right.

    So 1 << 31 means 1 * 2 * 2 * 2 ... 31 times which means 2^31 (so 32 bits)