Bitwise Manipulation - Shifts

Computer Science: OCR A Level, topic 4.1.18

Bitwise Manipulation - Shifts

Bitwise manipulation is the act of modifying data by changing the bits within individual bytes.

Logical shift right

Logical shift right

  • A logical shift right moves each of the bits in a byte one place to the right.
  • The ‘least significant bit’ (LSB) on the right is lost and the empty space for the ‘most significant bit’ (MSB) is filled with a ‘0’.
  • For example, 1 0 1 0 1 0 0 0 →\rightarrow 0 1 0 1 0 1 0 0
  • A logical shift right is identified with a triple chevron ‘>>>’.
Logical shift left

Logical shift left

  • A logical shift left moves each of the bits in a byte one place to the left.
  • The MSB on the left is lost and the empty space for the LSB is filled with a ‘0’.
  • For example: 1 0 1 0 1 0 0 0 →\rightarrow 0 1 0 1 0 0 0 0
  • A logical shift left is identified with a ‘<<<’.
Arithmetic shift right

Arithmetic shift right

  • Arithmetic shifts are almost the same as logical shifts, except the MSB is a sign bit and always remains the same.
  • An arithmetic shift right has the following result:
  • 1 0 1 0 1 0 0 0 →\rightarrow 1 0 0 1 0 1 0 0
  • This has the effect of dividing the original number by 2.
  • An arithmetic shift right is identified with a '>>'.
Arithmetic shift left

Arithmetic shift left

  • An arithmetic shift left has the following result:
  • 1 0 1 0 1 0 0 0 →\rightarrow 1 1 0 1 0 0 0 0
  • This has the effect of multiplying the original number by 2.
  • An arithmetic shift left is identified with a '<<'.
Circular shift

Circular shift

  • With a right circular shift, the same procedure applies.
  • However, instead of losing the LSB in a right shift, it ‘wraps around’ and becomes the MSB.
  • 1 0 1 0 1 0 0 0 →\rightarrow 0 1 0 1 0 1 0 0
  • Similarly, with a left circular shift, the MSB becomes the new LSB.
  • 1 0 1 0 1 0 0 0 →\rightarrow 0 1 0 1 0 0 0 1

Test yourself on Bitwise Manipulation - Shifts

Practise this topic for free