# C Programming Shift Operators

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.

Operator | Operation | Example | Result |
---|---|---|---|

« | Shift Left | x << y | Shift x by y bits to the left |

» | Shift Right | x >> y | Shift x by y bits to the right |

## Logical Shift Right (Zero Fill)

2

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)

2

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.

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

### Divide by 2

2

3

int y;

y = x / 2; //y=10

5 assembly instructions!

21 clock cycles!

### Right Shift by 1

2

3

int y;

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

3 assembly instructions!

3 clock cycles!