Part of the series

Several example codes

~2 min read • Updated Oct 1, 2025

Program Overview

This Python program reads an integer number and a bit index n, then displays the value of the n-th bit in the binary representation of the number.
Bit indexing starts from 0 (least significant bit).


Python Code:


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

# Check if n is within valid range
if n < 0 or n >= num.bit_length():
    print("Invalid bit index. It must be between 0 and", num.bit_length() - 1)
else:
    # Extract the n-th bit
    bit_value = (num >> n) & 1

    # Display result
    print("\n--- Result ---")
    print(f"Binary of {num}: {bin(num)}")
    print(f"Bit at position {n}: {bit_value}")

Sample Output:


Enter an integer number: 13  
Enter the bit index (n): 2  

--- Result ---
Binary of 13: 0b1101  
Bit at position 2: 1

Step-by-Step Explanation:

- The user enters an integer and a bit index
- The program checks if the index is valid (within the bit length of the number)
- It uses bitwise shift and AND operations to extract the desired bit
- The result is printed along with the binary form of the number


Written & researched by Dr. Shahin Siami