0
0
PythonProgramBeginner · 2 min read

Python Program to Toggle Bits of a Number

To toggle bits of a number in Python, use the XOR operator ^ with a mask of 1s like number ^ ((1 << bit_length) - 1) where bit_length is the number of bits in the number.
📋

Examples

Input5
Output2
Input0
Output1
Input15
Output0
🧠

How to Think About It

To toggle bits of a number, think of flipping every 0 to 1 and every 1 to 0 in its binary form. We create a mask with all bits set to 1 for the length of the number's binary form, then use the XOR operator ^ to flip bits where the mask has 1s.
📐

Algorithm

1
Get the input number.
2
Find the number of bits needed to represent the number in binary.
3
Create a mask with all bits set to 1 for that bit length.
4
Use XOR <code>^</code> between the number and the mask to toggle bits.
5
Return or print the toggled result.
💻

Code

python
def toggle_bits(number):
    bit_length = number.bit_length() or 1
    mask = (1 << bit_length) - 1
    return number ^ mask

# Example usage
num = 5
print(toggle_bits(num))
Output
2
🔍

Dry Run

Let's trace the number 5 through the code to toggle its bits.

1

Calculate bit length

5 in binary is 101, so bit_length = 3

2

Create mask

mask = (1 << 3) - 1 = 8 - 1 = 7 (binary 111)

3

Toggle bits using XOR

5 ^ 7 = 101 ^ 111 = 010 (binary) = 2

StepNumber (binary)Mask (binary)Result (binary)Result (decimal)
Initial101111N/A5
After XOR1011110102
💡

Why This Works

Step 1: Find bit length

We find how many bits the number uses with bit_length() to know how many bits to toggle.

Step 2: Create mask

The mask has all bits set to 1 for the number's bit length, so XOR flips all bits.

Step 3: Toggle bits with XOR

XOR with 1 flips bits: 1 becomes 0, 0 becomes 1, toggling all bits of the number.

🔄

Alternative Approaches

Toggle bits using string manipulation
python
def toggle_bits_str(number):
    binary_str = bin(number)[2:]
    toggled_str = ''.join('1' if b == '0' else '0' for b in binary_str)
    return int(toggled_str, 2)

print(toggle_bits_str(5))
This method uses string conversion and is less efficient but easy to understand.
Toggle bits with fixed bit size (e.g., 8 bits)
python
def toggle_bits_fixed(number, bits=8):
    mask = (1 << bits) - 1
    return number ^ mask

print(toggle_bits_fixed(5))
This toggles bits assuming a fixed size, useful for bytes but may toggle leading zeros.

Complexity: O(1) time, O(1) space

Time Complexity

The operations use fixed bitwise calculations and no loops, so time is constant O(1).

Space Complexity

Only a few variables are used for mask and bit length, so space is constant O(1).

Which Approach is Fastest?

The bitwise XOR method is fastest and most memory efficient compared to string manipulation.

ApproachTimeSpaceBest For
Bitwise XOR with dynamic maskO(1)O(1)General use, efficient toggling
String manipulationO(n) where n is bit lengthO(n)Easy to understand, less efficient
Fixed bit size XORO(1)O(1)When toggling fixed-size data like bytes
💡
Use number.bit_length() to find how many bits to toggle dynamically.
⚠️
Beginners often forget to create a mask of the correct bit length, causing wrong toggling results.