How do I do a bitwise Not operation in Python?

The problem with using ~ in Python, is that it works with signed integers. This is also the only way that really makes sense unless you limit yourself to a particular number of bits. It will work ok with bitwise math, but it can make it hard to interpret the intermediate results.

For 4 bit logic, you should just subtract from 0b1111

0b1111 - 0b1100  # == 0b0011

For 8 bit logic, subtract from 0b11111111 etc.

The general form is

def bit_not(n, numbits=8):
    return (1 << numbits) - 1 - n

Leave a Comment