[issue29710] Incorrect representation caveat on bitwise operation docs

Mark Dickinson report at bugs.python.org
Sun May 21 05:25:45 EDT 2017


Mark Dickinson added the comment:

So on re-reading the docs, I think we're misinterpreting this part:

> this assumes that there are enough bits so that no overflow occurs during the operation

One way to think of | and & (and ~ and ^, too):

1. Find a positive integer n such that both x and y can be represented *without overflow* in n-bit two's complement.

2. Do the computation x | y (or x & y, x ^ y, ~x, as appropriate) in n-bit two's-complement arithmetic, giving an n-bit two's complement result that we re-interpret as a signed integer in the usual way.

I think the "so that no overflow occurs" refers to choosing n sufficient large in the first step above. Note that it doesn't matter what value of n we choose to use, so long as it's large enough: evaluating 5 & -17 will work just as well using 8-bit two's complement as using 23-bit two's complement --- we'll get the same result either way.

(I personally tend to find it easier to think in terms of the infinite 2-adic representation, which is essentially what you get by extending the 0 or 1 sign bit leftwards into an infinite string of 0s or 1s.)

----------

_______________________________________
Python tracker <report at bugs.python.org>
<http://bugs.python.org/issue29710>
_______________________________________


More information about the Python-bugs-list mailing list