bitwise not - not what I expected

Irmen de Jong irmen at -NOSPAM-REMOVETHIS-xs4all.nl
Sun Aug 17 11:21:11 EDT 2003


While others explained how the ~ operator works, let me suggest
another possibility: the bitwise exclusive or.

 >>> def bin(i):
...     l = ['0000', '0001', '0010', '0011', '0100', '0101', '0110', '0111',
...          '1000', '1001', '1010', '1011', '1100', '1101', '1110', '1111']
...     s = ''.join(map(lambda x, l=l: l[int(x, 16)], hex(i)[2:]))
...     if s[0] == '1' and i > 0:
...         s = '0000' + s
...     return s
...
 >>> bin(18)
'00010010'
 >>> ~18
-19
 >>> bin(~18)     # tricky...
'11111111111111111111111111101101'
 >>> ~18 & 0x1f
13
 >>> bin(~18 & 0x1f)
'00001101'
 >>> 18 ^ 0x1f        # XOR!
13
 >>> bin(18 ^ 0x1f)   # XOR
'00001101'
 >>>


You still have to think about the number of bits you want to invert.
x ^ 0x1f inverts the 5 least significant bits of x.
x ^ 0xff inverts the 8 least significant bits of x, and so on.


--Irmen de Jong





More information about the Python-list mailing list