🎓 A1Learner
🔍

Python Bitwise Operators

A bit is one switch inside a number. Bitwise operators work on these bits, one column at a time.

And and or on bits

Read each column on its own. The results are 8 and 14 in decimal.

print(0b1010 & 0b1100)
print(0b1010 | 0b1100)

Exclusive or and not

The sign ^ keeps columns where the bits differ. The sign ~ flips all bits.

print(0b1010 ^ 0b1100)
print(~5)

Shift bits left and right

Shifting left adds a zero bit at the end. Shifting right drops bits from the end.

print(1 << 3)
print(16 >> 2)

Keep low bits with a mask

The mask has ones only in the low four places. The sign & keeps just those bits.

value = 0b11110101
mask = 0b00001111
print(value & mask)

Example

READ = 0b0001
WRITE = 0b0010
RUN = 0b0100
DELETE = 0b1000

user = READ | WRITE | DELETE
print("User bits:", format(user, "08b"))
print("Can read:", bool(user & READ))
print("Can write:", bool(user & WRITE))
print("Can run:", bool(user & RUN))
print("Can delete:", bool(user & DELETE))

Key points

  • Bit: a single 0 or 1 inside a number.
  • Use 0b to write a number in binary, like 0b1010.
  • The sign & gives 1 only where both bits are 1.
  • The sign | gives 1 where at least one bit is 1.
  • The sign ^ gives 1 where the two bits differ.
  • Mask: a bit pattern you combine with & to keep only some bits.
  • enum.Flag in the OOP lessons builds named flags like these.

In this example, each permission owns one bit. The sign | joins the bits for read, write, and delete into user. The format call prints user as eight bit characters, so the output is exact. Each check uses & with one flag as a mask. A result of 0 means that bit is off, and bool turns it into False. Real code often uses enum.Flag for this same idea, with names instead of raw bits.

Note

The sign ~ flips every bit.

Python ints have endless sign bits, so ~5 is -6.

Try it Yourself

Edit the code, then press Run.

Running is simulated · Python Playground

Exercise

What does a mask do in bitwise code?