Woody1193
Woody1193

Reputation: 8010

Python and Bitwise Operations

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.

Upvotes: 0

Views: 348

Answers (1)

hiro protagonist
hiro protagonist

Reputation: 46921

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.

Upvotes: 2

Related Questions