Check whether kth bit is set or not in Python

Bit plays a very important role while solving programming problems. In this article, we have discussed how to check whether the kth bit of a number is set or not in Python. We have also put the code in this tutorial.

Python program to check if kth bit of a number is set or not

So let’s see the input and corresponding output for better understanding:

Input : num = 9, k = 1

Output: Set

9 in bit representation is 1001, hence its 1st bit is set

Method-1:

We can check whether kth bit of a number is set or not with the help of left shift operator.

Algorithm:

  1. Firstly compute 1<<(k-1) and store it in a variable say var, hence var=1<<(k-1). var stores a number which has only its kth bit set.
  2. In this step you have to perform bitwise AND of number and var. If this gives a non-zero number then kth bit of number is set otherwise not.
# Function to check if kth bit of a number is set or not
def isSet(num, k):
  var = (1 << (k - 1)) 
  if num & var: 
    print( "{}st bit of {} is set".format(k,num)) 
  else: 
    print("{}st bit of {} is not set".format(k,num)) 

# Driver program 
num = 9
k = 1
isSet(num, k) 

 
Output:

1st bit of 9 is set

Method-2:

We can do this using right shift operator also.

  1. Firstly compute num>>(k-1) and store it in a variable say var, hence var=num>>(k-1). var will have its last bit equal to 1 if k-th bit is set else it will have last bit equal to 0.
  2. In this step you have to perform bitwise AND of 1 and var. If this gives a non-zero number then kth bit of number is set otherwise not.
# Function to check if kth bit of a number is set or not
def isSet(num, k): 
  var = (num>>(k-1))
  if 1 & var: 
    print( "{}st bit of {} is set".format(k,num)) 
  else: 
    print("{}st bit of {} is not set".format(k,num)) 

# Driver program 
num = 9
k = 1
isSet(num, k) 
Output:

1st bit of 9 is set

 

Leave a Reply