Bit Shifts

Learn what bit shifts are and how we can use them in Bash.

What are bit shifts?

A bit shift changes the positions of the bits in a number.

There are three types of bit shifts:

  1. Logical
  2. Arithmetic
  3. Circular

The simplest shift type is the logical one. Let’s consider it first.

Any bit shift operation takes two operands. The first one is some integer in which you want to shift some bits. The second operand is the number of bits to move.

Logical bit shift

Here is an algorithm for doing the logical bit shift:

  1. Represent the integer in the two’s complement.

  2. Discard the required amount of bits on the RHS for the right shift and the LHS for the left shift.

  3. Append zeroes on the opposite side of the number. This is LHS for the right shift and RHS for the left shift. The amount of zeroes matches the number of shifted bits.

Logical right shift

To better ...