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.

4
  • It starts from the LSB Commented Sep 20, 2015 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. Commented Sep 20, 2015 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. Commented Sep 20, 2015 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 ==. Commented Sep 20, 2015 at 19:50

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

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 lists, or use len instead of int in the case of strs.
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!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.