Let's talk about the bitwise operators in python,

<<, >>, &, |, ~, ^.

They usually operate on numbers but instead of treating them like a single value, they treat them as a string of bits written in 2's complement binary. 2's complement is calculated by inverting the bits and adding 1.

2's Complement Binary form for Positive Integers

$ (2)_{10} = 010 \\ (5)_{10} = 0101 \\ (9)_{10} = 01001 \\ (20)_{10} = 010100 $

2's Complement Binary form for Negative Integers

A negative integers -x is written in binary as x-1 and all the bits complemented. For example, -4 is complement(4-1) = complement(3) = ...1111111100.

The binary form of negative numbers in written with leading 1s instead on 0s. Python uses infinite number of bits. For example, -5 is treated by the bitwise operators in python as ...111111111011. -4 is treated by the bitwise operators in python as ...11111111100.

Bitwise Operators

Set Operations

Assume we have two sets A and B. We have the following set operations in python,