Algorithmscomplement logic

Complement Logic — NOT and Masks

TT
Testlaa Team
May 14, 20261 min read

Inside a fixed bit-width, complement with ^ all_ones_mask rather than infinite bits of Python integers.

Try this in Python

w = 4
all_ones = (1 << w) - 1
x = 0b0110
print(bin(x ^ all_ones))

Key takeaways

  • Define width w explicitly in problems about registers.
  • ~x in Python is unbounded two’s complement—mask after if needed.
  • Practice truth tables for small w.

Tags:

Bits & subset DPPythonStudents