Menu

Binary Shifts

Logical Shifts

A logical shift slides the bits of a binary pattern a number of places to the left or the right, and fills every position left empty with a zero. The pattern keeps the same width, and any bits pushed past the edge are lost rather than wrapped round to the other end.

Which side takes the zeros?

The direction of travel tells you which end needs filling: the gaps always appear behind the moving bits.

ShiftBits moveVacant positions filled with8-bit example
Logical lefttowards the leftzeros on the right0011 0100 becomes 0110 1000
Logical righttowards the rightzeros on the left0011 0100 becomes 0001 1010

Take 0011 0100, which is 52. Shifting it one place left moves every bit up a place value and puts a 0 in the right-hand gap, giving 0110 1000, which is 104. Shifting it one place right does the opposite: the bits step down a place value, a 0 fills the left-hand gap, and 0001 1010 is left, which is 26. If a 1 sits at the very edge when it moves, it drops out of the pattern and is discarded.

0011 0100 (52) shifted logically left one place gives 0110 1000 (104) and right one place gives 0001 1010 (26), with 0s filling the gaps and the dropped bit marked.

Why unsigned integers use logical shifts

In an unsigned integer every single bit is a value bit — none of them is reserved for anything else — so a zero dropped into a gap can never spoil the number, and the shifted pattern is still a valid unsigned value. Filling with 0 is simply the safe choice. A signed integer stores its sign in the leftmost bit, so a zero in the left-hand gap would not do; signed numbers use the arithmetic shift instead.

Practise this