Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

bit-shift
operator
operators

What are bit-shift operations?

Educative Answers Team

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.

Left-Shift

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 00 is inserted to the rightmost end. This is illustrated in the diagram below:

svg viewer

Also, note that the result of a left-shift operation is a multiplication by 2n2^n, where nn is the number of shifted bit positions. In the diagram above, the initial decimal number is 1010 and, after a single left-shift, the decimal number is 2020.

Logical Right-Shift

A logical right-shift of one position moves each bit to the right and inserts a 00 at the other end. This is illustrated below:

svg viewer

For positive numbers, a single right-shift is equivalent to a division by 22. In the diagram above, the initial decimal number is 1010 and it is halved to 55 by a logical right-shift.

Arithmetic 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:

svg viewer

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.

RELATED TAGS

bit-shift
operator
operators
Copyright ©2022 Educative, Inc. All rights reserved
RELATED COURSES

View all Courses

Keep Exploring