Search code examples
logical-operatorsbit-shift

Logical left shift of 0


Here my question is why the logical left shift 0 is one. 1<<0 = 1, but how?

According to definition the logical left shift works by shifting the bits towards left by n bits.

Logical left shifts works by multiplying number with 2 n << number = 2*n*number; not in case of number=0;

Even if the 0 or the negative numbers are stored in two's complement, so for zero all the bits must be one, then how its logical left shift works.

1<<0 =1         1<<2=4
2<<0 =2         2<<2=8
3<<0 =3         3<<2=12

Solution

  • Bit shift left multiplies the right hand number by 2 to the power of the left hand side. For example: 1 << 2 is the same as 1 * 2^2 (where ^ represents exponent, not XOR).

    1 in binary is 0001, then bitshifting it by 0 won't do anything, which aligns with what you observed.

    So any number x << 0 is equivalent to x * 2^0, which is x * 1, which is just x.