0

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?

Melissa Stewart
  • 3,483
  • 11
  • 49
  • 88
  • 3
    Possible duplicate of [Why does (1 << 31) >> 31 result in -1?](https://stackoverflow.com/questions/26192284/why-does-1-31-31-result-in-1) – davidkonrad Nov 26 '17 at 18:07
  • 1
    `1 << 31` creates 2^31 and `2^31 - 1` is the maximum positive 32-bit signed number. – Sulthan Nov 26 '17 at 18:07
  • 2
    What language is this? – Bergi Nov 26 '17 at 18:25
  • 1
    This expression certainly does not check for a number being ***32*** bits, and would not work/compile at all in a significant number of languages. Which leads to @Bergi's question (beat my by 30 seconds), and perhaps the need for showing its context/origin. – tevemadar Nov 26 '17 at 18:25
  • 1
    @davidkonrad: How on earth is that a duplicate? It seems to be a different question entirely. – Mark Dickinson Nov 26 '17 at 18:37

1 Answers1

1

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' an 0 at the end of each number to multiply by 2 and in most language we can do this with this 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)

Franck
  • 71
  • 1
  • 2