Bitwise Operations

Bitwise Operations

Introduction

  • We are used to operations that can be applied to numbers (integers and floats), such as:
    • Addition
    • Subtraction
    • Multiplication
    • Division
  • And also operations that can be applied to strings, such as:
    • subString()
    • append()
    • split()
  • However there is another class of operations which can be applied directly to bits, we will cover 3 of them here:
    • AND
    • OR
    • XOR
  • It should also be noted, that although the bitwise operations are defined for single bits, they are applied to larger data types (such as integers). When a bitwise operation is applied to an integer, it is applied to each bit individually.

AND

  • the AND operator is a binary operator, it operates on two parameters of equal length (in bits).
  • IF c = a AND b, then c == 1 if and only if a == 1 and b == 1.
  • Example:
    a = 0011
    b = 1010
    c = 0010
  • Code (Python)
    def print_bits(i):
        print(bin(i)[2:].zfill(4))
    
    
    a = int('0011', 2)
    print_bits(a)
    
    b = int('1010', 2)
    print_bits(b)
    
    print_bits(a & b)

OR

  • the OR operator is a binary operator, it operates on two parameters of equal length (in bits).
  • IF c = a OR b, then c == 0 if and only if a == 0 and b == 0.
  • Example:
    a = 0011
    b = 1010
    c = 1011
  • Code (Python)
    def print_bits(i):
        print(bin(i)[2:].zfill(4))
    
    
    a = int('0011', 2)
    print_bits(a)
    
    b = int('1010', 2)
    print_bits(b)
    
    print_bits(a | b)

XOR

  • the XOR operator is a binary operator, it operates on two parameters of equal length (in bits).
  • XOR is short for 'exclusive OR', it is similar to OR, however if both a and b are set to 1 then c is set to 0.
  • IF c = a XOR b, then c == ! if and only if a OR b == 1 and a AND b == 0.
  • Example:
    a = 0011
    b = 1010
    c = 1001
  • Code (Python)
    def print_bits(i):
        print(bin(i)[2:].zfill(4))
    
    
    a = int('0011', 2)
    print_bits(a)
    
    b = int('1010', 2)
    print_bits(b)
    
    print_bits(a ^ b)