Check whether K-th bit is set or nots in Python

Suppose we have a number n and another value k. We have to check whether the k-th bit in n is set (1) or not. The value of k is considered from the right-hand side (1-indexed).

So, if the input is like n = 23, k = 3, then the output will be True as binary form of 23 is 10111, so the 3rd bit from the right is 1 (set).

Algorithm

To solve this, we will follow these steps ?

  • Shift n right by (k - 1) positions to bring the k-th bit to the least significant position
  • Perform bitwise AND with 1 to check if the least significant bit is set
  • If the result is 1, return True, otherwise return False

Method 1: Using Right Shift and AND

This approach shifts the bits right and checks the least significant bit ?

def is_kth_bit_set(n, k):
    temp = n >> (k - 1)
    return bool(temp & 1)

# Example usage
n = 23
k = 3
result = is_kth_bit_set(n, k)
print(f"Binary of {n}: {bin(n)}")
print(f"Is {k}-th bit set? {result}")
Binary of 23: 0b10111
Is 3-th bit set? True

Method 2: Using Left Shift and AND

Alternative approach that creates a mask by left-shifting 1 ?

def is_kth_bit_set_v2(n, k):
    mask = 1 << (k - 1)
    return bool(n & mask)

# Example usage
n = 23
k = 3
result = is_kth_bit_set_v2(n, k)
print(f"Binary of {n}: {bin(n)}")
print(f"Mask for position {k}: {bin(1 << (k - 1))}")
print(f"Is {k}-th bit set? {result}")
Binary of 23: 0b10111
Mask for position 3: 0b100
Is 3-th bit set? True

Testing Multiple Examples

def test_bit_checking():
    test_cases = [
        (23, 1),  # 10111 - 1st bit: 1
        (23, 2),  # 10111 - 2nd bit: 1  
        (23, 3),  # 10111 - 3rd bit: 1
        (23, 4),  # 10111 - 4th bit: 0
        (8, 4),   # 1000 - 4th bit: 1
        (8, 1)    # 1000 - 1st bit: 0
    ]
    
    for n, k in test_cases:
        result = is_kth_bit_set(n, k)
        print(f"n={n}, k={k}, binary={bin(n)}, {k}-th bit set: {result}")

test_bit_checking()
n=23, k=1, binary=0b10111, 1-th bit set: True
n=23, k=2, binary=0b10111, 2-th bit set: True
n=23, k=3, binary=0b10111, 3-th bit set: True
n=23, k=4, binary=0b10111, 4-th bit set: False
n=8, k=4, binary=0b1000, 4-th bit set: True
n=8, k=1, binary=0b1000, 1-th bit set: False

Comparison

Method Operation Time Complexity Space Complexity
Right Shift n >> (k-1) & 1 O(1) O(1)
Left Shift Mask n & (1 << (k-1)) O(1) O(1)

Conclusion

Both methods efficiently check if the k-th bit is set using bitwise operations. The right shift method moves the target bit to position 0, while the mask method creates a filter to isolate the target bit. Both have O(1) time and space complexity.

Updated on: 2026-03-25T14:36:37+05:30

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements