How to Compare Binary Number Bits in Python
Binary numbers are the foundation of computing, representing data as sequences of 0s and 1s. In Python, manipulating these bits directly (known as bitwise operations) allows for highly efficient data processing, flag management, and algorithm optimization. Unlike standard arithmetic comparisons (like > or ==), bitwise comparison involves examining specific bits within an integer to determine their state (set/on or unset/off).
This guide explores how to compare binary number bits using Python's bitwise operators (&, |, ^), detect specific bit patterns, and implement efficient masking techniques.
Understanding Binary Representation in Python
In Python, integers are stored as objects, but bitwise operators treat them as sequences of bits. You can visualize these bits using the bin() function.
- Prefix: Binary strings in Python start with
0b. - Bit Position: Indexing typically starts from the right (0-indexed). The rightmost bit is the Least Significant Bit (LSB).
number = 10 # Decimal
# Visualize binary
print(f"Decimal: {number}")
print(f"Binary: {bin(number)}")
# Define using binary literal
binary_val = 0b1010
print(f"Literal matches decimal? {binary_val == number}")
Output:
Decimal: 10
Binary: 0b1010
Literal matches decimal? True
Integers in Python have arbitrary precision. When performing bitwise NOT (~) on positive numbers, the result might look like a negative number due to two's complement representation.
Method 1: Using Bitwise AND (&) to Check Specific Bits
The most common comparison task is checking if a specific bit is "set" (equal to 1). You achieve this using the Bitwise AND operator (&) combined with a mask or a shifted 1.
Checking a Single Bit
To check if the bit at position n is 1, shift 1 left by n positions (1 << n) and perform an AND operation.
def check_bit(number, n):
"""Checks if the nth bit (0-indexed from right) is set."""
mask = 1 << n
if (number & mask) != 0:
return True
return False
# Number: 10 (Binary: 1010)
# Indices: 3210
val = 0b1010
# ✅ Check bit at index 1 (2nd from right) -> Should be 1
print(f"Is bit 1 set? {check_bit(val, 1)}")
# ✅ Check bit at index 2 (3rd from right) -> Should be 0
print(f"Is bit 2 set? {check_bit(val, 2)}")
Output:
Is bit 1 set? True
Is bit 2 set? False
Method 2: Using Bitwise XOR (^) to Find Differences
The Bitwise XOR operator (^) compares two numbers bit by bit. It returns 1 where the bits are different and 0 where they are the same. This is incredibly useful for finding discrepancies between two binary states.
a = 0b1010 # 10
b = 0b1100 # 12
# Compare bits
diff = a ^ b
print(f"A: {bin(a)}")
print(f"B: {bin(b)}")
print(f"Diff: {bin(diff)} (1 indicates difference)")
# Check if numbers are identical (XOR result is 0 if identical)
if diff == 0:
print("Numbers are identical in binary.")
else:
print("Numbers differ at specific bit positions.")
Output:
A: 0b1010
B: 0b1100
Diff: 0b110 (1 indicates difference)
Numbers differ at specific bit positions.
Method 3: Bit Masking for Multi-Bit Comparison
Sometimes you need to compare a subset of bits (e.g., the last 4 bits) rather than the whole number. This is done using a Mask. A mask is a binary number where 1s represent the bits you care about and 0s represent bits to ignore.
Example: Comparing only the last 4 bits
To isolate the last 4 bits, we use a mask of 0b1111 (decimal 15).
def compare_last_4_bits(num1, num2):
mask = 0b1111 # Selects only the last 4 bits
masked_1 = num1 & mask
masked_2 = num2 & mask
print(f"Num1 masked: {bin(masked_1)}")
print(f"Num2 masked: {bin(masked_2)}")
return masked_1 == masked_2
# 0b11110101 vs 0b00000101
# Different high bits, but same last 4 bits (0101)
val1 = 0b11110101
val2 = 0b00000101
is_match = compare_last_4_bits(val1, val2)
print(f"Last 4 bits match? {is_match}")
Output:
Num1 masked: 0b101
Num2 masked: 0b101
Last 4 bits match? True
Common masks:
0xFF(selects the last 8 bits / 1 byte)0b1(selects the last bit / checks for odd/even)
Conclusion
Comparing binary bits in Python relies on three core operators:
- Bitwise AND (
&): Essential for checking if specific bits are ON (1) or isolating parts of a number using a mask. - Bitwise XOR (
^): The standard tool for detecting differences between two numbers; it acts like a "not equal" operator for individual bits. - Bitwise Shifts (
<<,>>): Used to move bits into the correct position for comparison.
By combining masks with these operators, you can efficiently inspect and compare binary data without converting to strings.