bitwise not - not what I expected

Tim Peters at
Mon Aug 18 02:18:27 CEST 2003

[Michael Peuser]
>> I have the impression (may be wrong) that you are working under the
>> misconception that there can be a "natural" binary represensation of
>> negative numbers!? Three conventions have commonly been used so far:
>> 1- Complement
>> 2-Complement
>> Sign tag plus absolut binary values

[Elaine Jackson]
> The last alternative sounds like what I was assuming. If it is, I
> would argue that it's pretty darn natural. Here's a little function to
> illustrate what I mean:
> def matilda(n):     ##  "my tilde"
>     if 0<=n<pow(2,29):
>         for i in range(1,31):
>             iOnes=pow(2,i)-1
>             if n<=iOnes:
>                 return iOnes-n
>     else:
>          raise

As Carl Banks pointed out, under this meaning the fundamental identity

    ~~x == x

almost never holds.  For example, matilda(18) is 13, but matilda(13) is 2.
~ is its own inverse under Python's meaning.  You can see that formally by
algrebraic manipulation:

    ~~n = ~(-(n+1)) = -(-(n+1)+1) == n

or more easily by noting that ~x in Python acts the same as xor'ing x with
an infinite string of 1 bits.

More information about the Python-list mailing list