Bit Shifting

Bit Shifting

Introduction

  • Bit Shifting is an operation which shifts bits.
  • The bits within bytes can be shifted either left or right, by a specified amount.
  • Bits maybe lost if their index is shifted outside the range of the integer.
  • It is also referred to as 'bitwise shifting'.

Left Shifting

  • When left shifting, we are adding 0's to the right edge of the integer, moving existing bits left to accomodate this.
  • The left shift operator is <<.
  • It is a binary operator:
    • its first parameter is the integer you want to shift,
    • the second parameter is the amount you want to shift by

Example

a      = 0011
a << 1 = 0110

Code (Python)

def print_bits(i):
    print(bin(i)[2:].zfill(4))


a = int('0011', 2)
print_bits(a) # prints '0011'

aShifted = a << 1
print_bits(aShifted) # prints '0110'
  • In Python, the size of an integer is not fixed.
  • and so bits are not lost no matter how much you shift by.
  • In other languages where it is fixed, shifting a bit beyond the size of the integer will mean the bit is lost.

Right Shifting

  • When right shifting, we are adding 0's to the left edge of the integer.
    • moving existing bits right to accomodate this.
  • The right shift operator is >>
  • It is also a binary operator:
    • its first parameter is the integer you want to shift,
    • and the second parameter is the amount you want to shift by

Example

a      = 0011
a >> 1 = 0001

Code (Python)

def print_bits(i):
    print(bin(i)[2:].zfill(4))

a = int('0011', 2)
print_bits(a) # prints '0011'

aShifted = a >> 1
print_bits(aShifted) # prints '0001'