Pebellslearn by building
0%
RoadmapsMatrixCoursesSandboxSign in
Bitwise Operators  ›  Lesson

Shifts — Multiply and Divide by Powers of Two

Bitwise Operators 12 minShifting a number's bits left by k places multiplies it by 2 to the k, and shifting right by k places divides it by 2 to the k, discarding the remainder.

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 << k moves 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 >> k moves 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 >>>.

The shortcut

Turn shifts into powers of two: << k means × 2ᵏ, >> k means ÷ 2ᵏ, rounded down. No binary needed for everyday values.

Three shifts, no binaryStep 1 of 4
  1. 3 << 4

    2⁴ = 16, and 3 × 16 = 48.

Drills

Answer fast — trust the rule.

quick drill

What is 3 << 4?

quick drill

What is 100 >> 3?

quick drill

What does 1 << 5 produce?

quick drill

In an unsigned 8-bit value, what is 200 << 1?

Remember

  • << k multiplies by 2ᵏ; >> k divides by 2ᵏ and rounds down.
  • 1 << k is the number with only bit k set.
  • The trap: fixed-width values lose bits off the top, and right shifts of negatives vary by language.

Practice — level up

0/1 solved

Write your answer, then compare it with a rubric and a model answer.

ExplainShifting instead of multiplying

Compute 5 << 3 and 45 >> 2, showing the bits. Explain why a left shift multiplies by a power of two, what happens to the bits that fall off a right shift, and what can go wrong when shifting left in a fixed 8-bit value.