pythonbinarybit-manipulationbitboolean-algebra

Why is 1<<3 + 1<<4 = 256?


I thought it would be equal to 1<<7 == 128, but why is it equal to 1<<8 == 256? Could u please explain the algebra of x<<y + x<<z operations?

python interpreter


Solution

  • This is because of the python order of operations, where addition is evaluated before the left shift operator. The expression is equivalent to

    (1<<(3+1))<<4