0

How does Python do bitwise operations? Is it from LSB to MSB, or the opposite? And how does Python do operations on numbers with different numbers of bits? For instance, suppose I had:

A = 0000 1000 1111 1001 0101
B = 0110 1010
C = (A & B) is not 0

If Python starts operations from the MSB on each, this will evaluate to True but if it starts operations from the LSB on each, it will evaluate to False.

Woody1193
  • 7,252
  • 5
  • 40
  • 90
  • It starts from the LSB – Padraic Cunningham Sep 20 '15 at 19:36
  • 1
    **Note:** the fact that `is not 0` will work work as intended (on CPython) is only due to luck. You *must* use `!= 0` to have a program that have the correct semantics according to the language. There could be an implementation of python were `C` is *always* false for the simply fact that `is not` is comparing identities and not values, independently of the value of `A & B`. The documentation is pretty clear about which objects are singletons. They are things like `None`, `True`, `False`, `Ellipsis`, `NotImplemented`. Numbers are *not* guaranteed to be singletons. – Bakuriu Sep 20 '15 at 19:42
  • @Bakuriu Yeah, actually I discovered that one myself just now. Actually, that's what prompted this question. I was and-ing two 200+ bit strings together and kept getting false `true` values. – Woody1193 Sep 20 '15 at 19:48
  • As a reference: use `is` only with `None` or when you need a sentinel value (in which case you'll have: `sentinel = object(); #do stuff; if somethign is sentinel`). The other singletons almost never occur in real python code and all other cases require to use `==`. – Bakuriu Sep 20 '15 at 19:50

1 Answers1

2

to enter numbers in binary prepend an 0b (and leave out the spaces) just as you would with 0x for hex numbers:

A = 0b00001000111110010101
B = 0b01101010
C = (A & B) is not 0

you can check how python interprets this by printing it out (as binary and hex for example):

print('{0:b} {0:x}'.format(A))
# 1000111110010101 8f95

as you see: it starts from the LSB.

also note a python quirk when comparing integers with is: "is" operator behaves unexpectedly with integers . therefore == may be the safer option.

Community
  • 1
  • 1
hiro protagonist
  • 44,693
  • 14
  • 86
  • 111
  • 1
    It's not a quirk. `is` checks *object identity*. `==` compares the *values*. Using one in place of the other is like using `.append()` instead of `.pop()` with `list`s, or use `len` instead of `int` in the case of `str`s. – Bakuriu Sep 20 '15 at 19:48
  • the quirk is that numbers up to 255 are singletons (`is` will work up to there). the ones above are not. the distinction between `is` and `==` is perfectly sound! – hiro protagonist Sep 20 '15 at 20:00