A bit-shift moves each digit in a number’s binary representation left or right. Within right-shifts, there are two further divisions: logical right-shift and arithmetic right-shift. A left-shift is represented by the <<
operator, while a right-shift is represented by the >>
operator.
When shifting to the left, the leftmost digit in the binary representation of a number (also known as the most-significant bit) is lost and a is inserted to the rightmost end. This is illustrated in the diagram below:
Also, note that the result of a left-shift operation is a multiplication by , where is the number of shifted bit positions. In the diagram above, the initial decimal number is and, after a single left-shift, the decimal number is .
A logical right-shift of one position moves each bit to the right and inserts a at the other end. This is illustrated below:
For positive numbers, a single right-shift is equivalent to a division by . In the diagram above, the initial decimal number is and it is halved to by a logical right-shift.
An arithmetic right-shift of one position moves each bit to the right by one step. The least significant bit (rightmost bit) is discarded and the vacant bit (leftmost bit, also known as the most significant bit) is filled with the value of the original most significant bit. This is illustrated below:
Hence, if a number is encoded using two’s complement, then an arithmetic right-shift preserves the number’s sign, while a logical right-shift makes the number positive.