Logical Shifts

What are Logical Shifts?

  • Logical shifts are the process of moving the bits in a binary number to the left or right by a specified number of places
  • Bitwise manipulation uses logical operators like AND, OR, XOR, and NOT to manipulate binary numbers

Logical Shifts

  • Logical binary shifts are operations performed on binary numbers where all the bits in the number are moved left or right by a specified number of positions
  • These shifts are commonly used in computer programming and digital systems
  • There are two types of logical binary shifts: Left and Right

Example left shift

The following number is shifted by two places to the left.

Example Left shift

Original number: 00001110 = 14

Left shift (2) result: 00111000 = 56

Each left shift has doubled the number:

  • Original value = 14
  • Left shift 1 - Doubled the number to 28
  • Left shift 2 - Doubled the number to 56

Example right shift

The following number is shifted by three places to the right.

Example Right Shift

Original number: 11001000 = 200

Right shift (3) result: 00011001 = 25

Each right shift has halved the number:

  • Original value = 200
  • Right shift 1 - Halved the number to 100
  • Right shift 2 - Halved the number to 50
  • Right shift 3 - Halved the number to 25

Bitwise Manipulation

What is a mask?

  • A mask is a binary number used in bitwise operations to isolate, modify, or test specific bits in another binary value
  • Think of a mask as a filter: it lets certain bits through and blocks others, depending on the bitwise operation being used

Why use a mask?

  • To extract certain bits from a binary number (e.g. the lower 4 bits)
  • To set specific bits to 1
  • To clear specific bits (set them to 0)
  • To toggle (flip) specific bits

Bitwise AND operation

If both bits are 1 in the binary number and the mask, the result will be 1. Otherwise, the result will be 0.

Description1286432168421
Binary10111001
Mask00110000
Result00110000

Bitwise OR operation

If either bit is 1 in the binary number or the mask, the result will be 1. Otherwise, the result will be 0.

Description1286432168421
Binary11001010
Mask01110000
Result11111010

Bitwise XOR operation

If only 1 of the bits is 1 in the binary number or the mask, the result will be 1. Otherwise, the result will be 0.

Description1286432168421
Binary10101010
Mask00110000
Result10011010