all Python 3Algorithms & data structuresterm
Bitwise operations
bitwise operations
& (AND), | (OR), ^ (XOR), ~ (NOT), << (left shift), >> (right shift). Used for masks, optimization and cryptography.
Syntax
a & b # AND
a | b # OR
a ^ b # XOR
~a # NOT
a << n # left shift
a >> n # right shift
Python ints are unbounded, so << never overflows, >> keeps the sign, and ~x is exactly -x-1 (~5 == -6) because negatives behave as an infinite two's-complement pattern. Bitwise operators bind tighter than comparisons but looser than arithmetic, so x > 0 & mask parses as x > (0 & mask) — parenthesise anything mixed. And & is not and: there is no short-circuiting, both operands are always evaluated.
Examples
# Базовые операции
print(0b1010 & 0b1100) # → 8 (AND, это 0b1000)
print(0b1010 | 0b1100) # → 14 (OR, это 0b1110)
print(0b1010 ^ 0b1100) # → 6 (XOR, это 0b0110)
print(~0b1010) # → -11 (NOT)
print(1 << 3) # → 8 (2^3)
print(16 >> 2) # → 4 (16/4)
# Проверка чётности
def is_even(n): return (n & 1) == 0
print(is_even(4)) # → True
print(is_even(7)) # → False
# Умножение/деление на степень двойки
print(5 << 2) # → 20 (5*4)
print(20 >> 2) # → 5 (20/4)
# XOR: swap без третьей переменной
a, b = 5, 3
a ^= b; b ^= a; a ^= b
print(a, b) # → 3 5
# Маска битов
def get_bit(n, i): return (n >> i) & 1
def set_bit(n, i): return n | (1 << i)
def clear_bit(n, i): return n & ~(1 << i)
n = 0b1010
print(get_bit(n, 1)) # → 1
print(bin(set_bit(n, 2))) # → 0b1110
print(bin(clear_bit(n, 3))) # → 0b10 — ведущие нули bin() не пишет
# Подсчёт единичных бит (popcount)
def popcount(n): return bin(n).count('1')
print(popcount(255)) # → 8
print(popcount(0)) # → 0
# XOR: найти уникальный элемент
def find_unique(arr):
result = 0
for x in arr: result ^= x
return result
print(find_unique([2,3,2,4,3])) # → 4
See also
Open in the full glossarydocs.python.orgReport an inaccuracy