new bitwise module [was Re: Discussion: new operators ...]

Tim Peters tim_one at email.msn.com
Wed Aug 2 22:26:35 EDT 2000


[Rainer Deyke]
> All bitwise operators except ~ (which could be redefined as
> ~a = a ^ 0xffffffff, with strange but predictable results
> for a > 0xffffffff) still make sense for long integers.

[Andrew Kuchling]
> Why couldn't ~ just assume twos-complement and have ~a = -(a+1)?  (Or
> whatever the expression for twos-complement bitwise negation works out
> to; I never remember if it's +1 or -1.)
>
> >>> ~12345678901234567890L
> -12345678901234567891L

[Rainer Deyke]
> Because that leaves ~0 inconsistent with existing code.

As I mentioned before, ~ is already implemented(!) for longs in Python, and
already makes perfect sense if you view longs as unbounded bitstrings --
which is hardly a stretch when talking about *bit* operators <wink>.

Since the meaning of ~a is to flip each bit, it's the same as subtracting a
from an infinite string of 1 bits.  -a in two's complement is the result of
subtracting a from (in effect) an infinite string of 0 bits, so to get
from -a to ~a you need to subtract 1:  ~a = -a - 1, which equals -(a+1) just
as Andrew said:

>>> ~0L
-1L
>>> -(0L+1)
-1L
>>>

Same thing.  This is "inconsistent" with ~0 only in the sense that ~0
necessarily consists of a finite number of 1 bits, whereas ~0L contains an
unbounded number of 1 bits:

>>> ~0L & 1    # what's "the last" bit?
1L
>>> (~0L >> 50000) & 1   # how about 50000 "to the left"?
1L
>>> ~0L >> 50000   # if it's infinite, this should equal ~0L too!
-1L
>>>

It's wholly consistent already.  Given the same numerical inputs, the same
bit expressions computed via longs or via ints are strongly related in that
the result of the int computation consists of the rightmost N bits of the
result of the long computation, where N is the number of bits in an int.
This is as true of ~0 as of any other bit expression:

>>> ~0 & 0xffffffffL
4294967295L
>>> ~0L & 0xffffffffL
4294967295L
>>>

each-fiction-needs-to-be-viewed-on-its-own-terms-ly y'rs  - tim






More information about the Python-list mailing list