256 – Bit manipulations

256 – Bit manipulations#

Python defines six bitwise operations: left and right shifts, bitwise AND, bitwise OR, bitwise inversion, and bitwise XOR. Elegant weapons for a more… civilised age.[1]

  • Bit shifting:

bin(73)       # 0b1001001
bin(73 << 2)  # 0b100100100
bin(73 >> 2)  # 0b10010

Shifting left will add zeroes on the right of the binary representation of the number and shifting right will drop digits.

  • Bitwise AND:

bin(73)       # 0b1001001
bin(37)       # 0b 100101
bin(73 & 37)  # 0b      1

Bitwise AND keeps 1s in the positions that had exactly two 1s.

  • Bitwise OR and XOR:

bin(73)       # 0b1001001
bin(37)       # 0b 100101
bin(73 | 37)  # 0b1101101  # OR
bin(73 ^ 37)  # 0b1101100  # XOR

Bitwise OR keeps 1s in the positions that had at least one 1 while bitwise XOR keeps 1s in the positions that had exactly one 1.

  • Bitwise inversion:

bin(73)   #  0b1001001
bin(~73)  # -0b1001010

Bitwise inversion computes -(x+1).