Bitwise OR?

Tim N. van der Leeuw tim.leeuwvander at nl.unisys.com
Fri Mar 24 03:48:48 EST 2006


Actually, following up to my own reply:

3500 | 67 = 3567. So perhaps that sets your expectations for 3500 |
-67.

But try

 -3500 | -67

for fun: it is -3

Bitwise or is no arithmetic and if you want to predict something about
the resulting integers, you should know something about how they are
stored.

Negative integers are stored in 2-complement format: minus 1 is all
bits set to 1. Turning bits off makes it a more negative number (as
long as you don't touch the sign-bit) and turning more bits on makes it
a smaller negative number.

Doing bitwise-OR for the positive numbers 3500 and 67 results in 3567:
proof that they don't have any overlapping bits.
Know it turns out that 3500 and -67 have only overlapping bits:
therefore the result is -67. (adding the bits from 3500 to the bits of
-67 doesn't turn on any extra bits).

Use bit operators to manipulate bits, and think of the operands as sets
of bits. Bitwise OR is the union of 2 sets of bits.
Don't think of the operands to bit operators as numbers, and don't try
to do your sums using bitwise or!

:-)

--Tim




More information about the Python-list mailing list