Shifts — Multiply and Divide by Powers of Two
To multiply by 10 in decimal, you add a zero on the right: 37 becomes 370. Binary has the same trick, except each zero multiplies by 2. Processors can do this in a single fast step, and it is how you build the masks you will use in the next lesson.
The rule
Left by k multiplies by 2ᵏ; right by k divides by 2ᵏ and drops the rest.
- Left shift
x << kmoves every bit k places to the left and fills the gap with zeros. Every bit lands in a place worth 2ᵏ times as much, so the value is x × 2ᵏ. - Right shift
x >> kmoves every bit k places to the right. The k rightmost bits fall off and are lost, so the value is x ÷ 2ᵏ rounded down. The lost bits are exactly the remainder.
5 = 00000101
5 << 3 = 00101000 = 40 (5 × 8)
45 = 00101101
45 >> 2 = 00001011 = 11 (45 ÷ 4 = 11 remainder 1)The most common shift of all is 1 << k, which makes a number with only bit k set: 1 << 0 is 1, 1 << 3 is 8, 1 << 10 is 1024.
Two cautions. In a fixed width (like an 8-bit or 32-bit integer), bits shifted off the top are lost too, so the "multiply" silently goes wrong. Python's integers grow as needed, but C, Java and Go's do not. And right-shifting negative numbers depends on the language: some copy the sign bit in from the left (arithmetic shift), some fill with zeros (logical shift). Java even has two operators, >> and >>>.