Numbers and bits · 2 / 15 Theory

Bitwise operators

Bitwise operators work on each bit of the integers separately. They are very fast and let you solve some problems with an elegance that is hard to match.

a, b = 0b1100, 0b1010
print(f"{a & b:04b}")     # 1000   AND: 1 if both are 1
print(f"{a | b:04b}")     # 1110   OR: 1 if either is 1
print(f"{a ^ b:04b}")     # 0110   XOR: 1 if they differ
print(f"{a >> 2:04b}")    # 0011   shifting right = dividing by 4
print(f"{a << 1:05b}")    # 11000  shifting left = multiplying by 2
print(~5)                 # -6     NOT: -(n + 1)

n = 12
print(n & (n - 1))        # 8      clears the lowest set bit
print(n & -n)             # 4      isolates the lowest set bit
print(bin(n).count("1"))  # 2      popcount
print(n.bit_length())     # 4      bits needed
OperatorMeaningExample
&AND12 & 10 → 8
|OR12 | 10 → 14
^XOR (exclusive or)12 ^ 10 → 6
~NOT (-(n+1))~5 → -6
<<, >>Shifts1 << 4 → 16
  • XOR satisfies a ^ a == 0 and a ^ 0 == a: it serves to cancel pairs, swap values or find the number without a pair.
  • n & (n - 1) clears the lowest set bit. It is 0 only if n has a single bit, that is, if it is a power of two.
  • n & -n isolates the lowest set bit.
  • Python integers have no fixed size, so ~ and negatives behave as if they had infinite ones on the left. To get the value in n bits, apply & ((1 << n) - 1).

You practice it in Count set bits, Powers of two, The unpaired number and Two's complement.