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)
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)
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.
Note: This works for integers or fixed-point values.
Power of a Two Integer Divide vs. Shift in XC-16
Divide by 2
5 Assembly Instructions!
21 clock cycles!
Right Shift by 1
3 Assembly Instructions!
3 clock cycles!