Part of the series

Several example codes

~2 min read • Updated Oct 1, 2025

Program Overview

This Python program reads an integer and a bit index n from the user.
It toggles the nth bit of the number — flipping it from 0 to 1 or from 1 to 0.
Bit manipulation is done using the XOR operator with a bitmask.


Python Code:


# Read number and bit index from user
num = int(input("Enter an integer: "))
n = int(input("Enter the bit index to toggle: "))

# Validate bit index
if n < 0:
    print("Bit index cannot be negative.")
else:
    # Toggle the n-th bit using XOR
    toggled = num ^ (1 << n)

    # Display result
    print("\n--- Result ---")
    print(f"Original number: {num} → Binary: {bin(num)}")
    print(f"After toggling bit {n}: {toggled} → Binary: {bin(toggled)}")

Sample Output:


Enter an integer: 55  
Enter the bit index to toggle: 5  

--- Result ---
Original number: 55 → Binary: 0b110111  
After toggling bit 5: 23 → Binary: 0b010111

Step-by-Step Explanation:

- The user inputs an integer and a bit index
- A bitmask (1 << n) is created to target the desired bit
- The XOR operator flips the bit at position n
- The result is printed in both decimal and binary formats


Written & researched by Dr. Shahin Siami