C Programming Shift Operators

Last modified by Microchip on 2023/11/09 09:06

The shift operators move the bits in an operand left or right by the specified number of bits.

The left shift is fairly simple and operates the same way, regardless of the operand type.
The right shift operates differently, depending on whether the operand is signed or unsigned (see next slide).

With Shift Left, bits moved out on the left are lost, and the right side is zero-filled.
With Shift Right, if the type is unsigned, the left side is zero-filled, otherwise, the sign is extended. Bits moved out on the right are lost.

«Shift Leftx << yShift x by y bits to the left
»Shift Rightx >> yShift x by y bits to the right

Logical Shift Right (Zero Fill)

x = 250;     // x = 0b11111010 = 250
y = x >> 2;  // y = 0b00111110 = 62

If the operand is unsigned, a shift right performs a logical shift right in which the bits are moved to the right and the vacancies on the left are filled with zeros.

Arithmetic Shift Right (Sign Extend)

x = -6;        // x = 0b11111010 = -6
y = x >> 2;    // y = 0b11111110 = -2

If the operand is signed, a shift right performs an arithmetic shift right in which the vacant bits are filled with whatever the value of the most significant bit was before the shift. This is done to perform a sign extend when working with signed binary values.

Power of a 2 Integer Divide vs. Shift Right

If you are dividing by a power of 2, it is usually more efficient to use a right shift.

Right Shift

Note: This works for integers or fixed-point values.

Power of a Two Integer Divide vs. Shift in XC-16

Divide by 2

int x = 20;
int y;
y = x / 2;    //y=10

5 assembly instructions!
21 clock cycles!

Divide By Two

Right Shift by 1

int x = 20;
int y;
y = x >> 1;    //y=10

3 assembly instructions!
3 clock cycles!

Right Shift By 1