This Python program reads an integer from the user and inverts all of its bits.
Each bit is flipped: 1 becomes 0, and 0 becomes 1.
The inversion is performed using the XOR operator with a full-bit mask.
# Read an integer from the user
num = int(input("Enter an integer: "))
# Determine the bit length of the number
bit_length = num.bit_length()
# Create a mask with all bits set to 1
mask = (1 << bit_length) - 1
# Invert all bits using XOR
inverted = num ^ mask
# Display the result
print("\n--- Result ---")
print(f"Original number: {num} → Binary: {bin(num)}")
print(f"Inverted number: {inverted} → Binary: {bin(inverted)}")
Enter an integer: 55
--- Result ---
Original number: 55 → Binary: 0b110111
Inverted number: 8 → Binary: 0b1000
- The user inputs an integer
- The program calculates its bit length using bit_length()
- A mask of the same length with all bits set to 1 is created
- The XOR operator flips each bit of the number
- The result is printed in both decimal and binary formats