Count set bits using Python List comprehension


Set bits are the bits representing 1 in the binary form of a number. In this article we will see how to count the number of set bits in a given decimal number.

#53 in binary is: 110101
The number of set bits is the number of ones.
Here it is 4.

In the below program we take the number and convert it to binary. As the binary conversion contains 0b as the first two characters, we remove it using string splitting technique. Then use a for loop to count each bit of the binary number if that value of the digit is 1.

Example

 Live Demo

value = 59
#Check the binary value
print(bin(value))
#Remove the first two characters
bitvalue = bin(value)[2:]
print(bitvalue)
count = 0
for digit in bitvalue:
   if digit == '1':
      count = count+1
print("Length of set bits: ",count)

Output

Running the above code gives us the following result −

0b111011
111011
Length of set bits: 5

Updated on: 19-Dec-2019

88 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements