Learn Python
>>> operators.op_bitwise

Bitwise Operators in Python

#concept

Bitwise operators work directly on the binary representation of integers, one bit at a time. They come up less often than arithmetic or logical operators, but show up in flags, permission systems, and performance-sensitive code. Python supports & (AND), | (OR), ^ (XOR), ~ (NOT), << (left shift), and >> (right shift).

#how it works
1

& compares bit by bit

Keeps a 1 only where both numbers have a 1 in that position.

2

| compares bit by bit

Keeps a 1 where either number has a 1 in that position.

3

^ (XOR) compares bit by bit

Keeps a 1 only where the two bits differ.

4

<< shifts bits left

Each position shifted doubles the number.

5

>> shifts bits right

Each position shifted halves the number, rounding down.

#example
print(6 & 3)
print(6 | 3)
print(6 ^ 3)
print(1 << 4)
print(16 >> 2)
Output
2
7
5
16
4
16 is 110 in binary and 3 is 011; & keeps only the position where both have a 1, giving 010 = 2.
2| keeps a bit wherever either number has a 1, giving 111 = 7.
3^ keeps only the bits that differ between the two, giving 101 = 5.
41 << 4 shifts the bit pattern of 1 left by 4 positions, the same as multiplying by 2 four times: 1 × 16 = 16.
516 >> 2 shifts right by 2, the same as dividing by 2 twice: 16 / 2 / 2 = 4.
#variants

Using Bits as Flags

A common pattern for compactly storing several on/off settings in one number, combining them with | and checking them with &.

READ = 1
WRITE = 2
permissions = READ | WRITE
print(permissions)
Output
3

Fast Multiply by a Power of 2

Shifting bits left is a quick way to multiply by 2, though everyday Python code usually favors * for readability unless performance is critical.

doubled = 5 << 1
print(doubled)
Output
10
#use cases
Storing and checking multiple on/off flags compactly in permission systems or configuration settings
Low-level programming, such as working with network protocols or hardware registers
Performance-critical code needing the fastest possible multiply or divide by a power of two
Cryptography and hashing algorithms, which rely heavily on bitwise operations

Recommended resourcesAffiliate links · may earn us a commission

Recommended for learners

Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Pro code editor & AI assistantWrite, debug and explain code faster while you practice the patterns here.Try it free Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books

Practice what you learned

Re-implement each visualized algorithm in Python yourself — building beats watching.