Menu

Binary Shifts

Shifting Unsigned Integers

An unsigned integer is stored as a binary pattern in which every bit adds to the value. Moving that pattern sideways is called a shift, and it gives a quick way to multiply or divide by powers of two without carrying out a full calculation.

One place at a time

A left shift by one place moves every bit one position to the left, so each bit lands on a place value twice as large. The whole value therefore doubles. Starting with 00001101 (13), a left shift gives 00011010, which is 26.

A right shift by one place moves every bit one position to the right, so each bit lands on a place value half as large. The value halves. If the number is odd, the 1 bit that drops off the right-hand end is lost, so any remainder is discarded: 00001101 (13) shifted right becomes 00000110, which is 6, because 13 ÷ 2 = 6.5 and the 0.5 is thrown away.

00001101 (13) shifted left one place gives 00011010 (26); shifted right one place gives 00000110 (6), with the dropped 1 marked. Place values 128 to 1 sit under each row.

Several places at once

Each place you move doubles or halves the value again. A left shift by n places multiplies by 2 to the power n, and a right shift by n places divides by 2 to the power n, discarding any remainder. So two places means multiply or divide by 4, and three places means multiply or divide by 8.

Using the same 8-bit pattern 00001101 (13):

ShiftResultDenaryCalculation
Left 1000110102613 × 2
Left 2001101005213 × 4
Right 100000110613 ÷ 2, remainder 1 discarded
Right 200000011313 ÷ 4, remainder 1 discarded

The direction decides whether you multiply or divide, and the number of places decides which power of two you use. A left shift by three on 00001101 gives 01101000 (104), which is 13 × 8. A right shift by three gives 00000001 (1), because 13 ÷ 8 = 1 remainder 5, and that remainder is discarded.

Practise this