Python Program to Count Set Bits in a Number

Python program to count set of bits in number; Through this tutorial, i am going to show you how to count total number of bits or set of bits in python.

So in this tutorial, i will write a python program to count total number of bits or set of bits in a number.

Python Program to Count Set Bits in a Number

# write a python program to count total number of bits in a number
num = int(input("Please Enter any Number: "))
# use bin () method to get the binary value of a number 
# print binary value output will be 0b111101
print ("binary value of {0} is: {1}".format(num, bin(num)))
# store the length of the binary number
length = len(bin(num))
# to get exact length total number of bits
# subtract 2 from the length
length -=2
# print length
print ("total number of bits: ", length)

Output

Please Enter any Number:  13 
binary value of 13 is: 0b1101 
total number of bits:  4 

Recommended Python Tutorials

Leave a Comment