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
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…