abbieleigheventsstyling.com → data → python pandas folder → python bitwise operators
Posted on by Chandler James

python bitwise operators

Side-by-side comparison of binary numbers and their bitwise results using Python

Python bitwise operators perform direct manipulation of integer values at the binary level, treating each number as a sequence of bits. They operate on the individual bits of integers, enabling efficient data processing and low-level control.

These operators include AND (&), OR (|), XOR (^), NOT (~), left shift (<<), and right shift (>>). Each applies a specific logic function to corresponding bits in two operands. For example, 5 & 3 evaluates to 1 because the binary representation of 5 (101) and 3 (011) share only the least significant bit set.

Bitwise operations are foundational in systems programming, cryptography, compression algorithms, and embedded systems. They're faster than arithmetic equivalents in many cases, especially when working with flags, masks, or packed data structures.

How They Work

Every integer in Python is stored in two's complement form, allowing negative numbers to be handled consistently. Bitwise operations treat these values as sequences of 0s and 1s, applying logic rules bit by bit.

For instance, consider 12 << 1. Binary 12 is 1100. Shifting left by one position adds a 0 at the end, producing 11000, which equals 24. Left shift multiplies by 2^n; right shift divides by 2^n (integer division).

The XOR operator (^) returns 1 when bits differ. So 7 ^ 10 gives 13: 7 = 0111 10 = 1010 XOR = 1101 = 13.

Types and Syntax

Here are the six primary bitwise operators in Python:

Operator Name Function Example
& AND 1 if both bits are 1 6 & 3 → 2 (110 & 011 = 010)
| OR 1 if either bit is 1 6 | 3 → 7 (110 | 011 = 111)
^ XOR 1 if bits differ 6 ^ 3 → 5 (110 ^ 011 = 101)
~ NOT Inverts all bits ~6 → -7 (flips 110 to 001, then negates due to two's complement)
<< Left Shift Multiplies by 2^n 5 << 2 → 20 (101 becomes 10100)
>> Right Shift Divides by 2^n (floor) 20 >> 2 → 5 (10100 becomes 101)

NOT (~) behaves differently than expected due to two's complement. ~n equals -(n + 1). So ~5 is -6, not a positive number with flipped bits.

Common Use Cases

Bitwise operators are essential in setting and checking flags. For example, in a permissions system, each bit represents a privilege:

READ = 1     # 0001
WRITE = 2    # 0010
EXECUTE = 4  # 0100
DELETE = 8   # 1000

# Combine permissions
permissions = READ | WRITE  # 0011 = 3

# Check if user has read access
has_read = bool(permissions & READ)  # True

This pattern is standard in Unix file modes, where chmod uses bitwise combinations.

Another use is masking. To extract the last 4 bits of a byte, use & 15 (binary 1111). For example, 27 & 15 → 11 (11011 & 01111 = 01011).

They also appear in checksums and error detection. CRC algorithms rely heavily on bitwise shifts and XOR to generate hash-like values from raw data streams.

Common Misconceptions and Pitfalls

Many developers assume ~ flips bits in a positive way. But in Python, ~n produces a negative result. This is because Python uses arbitrary precision integers, so ~5 is not 0b...11111111111111111111111111111010 (as in C), but rather -6.

Another mistake is assuming bitwise operations work on strings. They do not. Attempting 5 & "101" raises TypeError. These operators only apply to integers.

Also, bitwise AND (&) is not the same as logical AND (and). The former operates on bits; the latter on boolean truth values. Using & with booleans leads to unexpected results:

True & False  # Returns 0, not False

Use and for conditionals, & for bit-level math.

Real-World Example: Color Channel Extraction

Consider a 32-bit color value encoded as RGBA: red (bits 24-31), green (16-23), blue (8-15), alpha (0-7). To extract green from 0xFFAABBCC:

color = 0xFFAABBCC  # 4277225004 in decimal
green = (color >> 16) & 0xFF  # Shift right 16, mask with 255
print(green)  # Output: 171

Result: 171, which corresponds to the green component. This method is standard in graphics libraries and image processing pipelines.

I've used this technique in a custom image parser to decode pixel data from binary files. Without bitwise shifts and masks, extracting channel values would require string parsing or complex arithmetic.

When Not to Use Them

Bitwise operators aren't ideal for high-level logic. Code like (flags & 4) == 4 is correct but less readable than named constants:

if has_execute_permission(flags):

Use them when performance matters or when interfacing with hardware, protocols, or binary formats. Avoid them in business logic unless clarity is preserved.

For learning, start with small integers. Use bin() to see binary representations: bin(13) returns '0b1101'. This helps debug bit patterns.

Further Reading

Understanding how integers are represented internally helps avoid confusion. The Python documentation explains bitwise operations under built-in numeric types.

Always test edge cases: large numbers, negative inputs, and mixed types. Python handles overflow gracefully, but semantics depend on correct assumptions about bit width.


Related Posts