bitwise not - not what I expected
Graham Fawcett
fawcett at teksavvy.com
Sun Aug 17 01:35:29 EDT 2003
Elaine Jackson wrote:
>Is there a function that takes a number with binary numeral a1...an to the
>number with binary numeral b1...bn, where each bi is 1 if ai is 0, and vice
>versa? (For example, the function's value at 18 [binary 10010] would be 13
>[binary 01101].) I thought this was what the tilde operator (~) did, but when I
>went to try it I found out that wasn't the case. I discovered by experiment (and
>verified by looking at the documentation) that the tilde operator takes n
>to -(n+1). I can't imagine what that has to do with binary numerals.
>
It has a lot to do with binary! Google for "two's complement".
In the meantime, try this:
>>> ~18 & 31
13
The '~' operator cannot care about precision -- that is, how many bits
you're operating on, or expecting in your result. In your example, you
represent decimal 18 as '10010', but '000000010010' is also correct,
right?
In two's complement math, both inverses, '01101' and '111111101101'
respectively, are equivalent to decimal -19.
And-ing with a mask that is the of length 'n' will ensure that you only
get the least significant n bits -- and this is what you're looking for.
Since you're operating on five bits in your example, I chose decimal 31,
or '11111'.
-- Graham
More information about the Python-list
mailing list