Python Count set bits in a range?


A given positive number when converted to binary, has a number of setbits. Set bits in a binary number is represented by 1. In this article we will see how to get the number of setbits in a given number after it is converted to binary value.

Using bin and slicing

In the below example we take a number and apply the bin function to get the binary value. Then we slice it to remove the prefixes added to a binary number and then apply the range function to get the coutn of setbits.

Example

 Live Demo

def SetBits_cnt(n, l, r):
   bin_val = bin(n)

   # Remove '0b' prefixed in bin_val conversion
   bin_val = bin_val[2:]
   print(bin_val)
   # reverse string
   bin_val = bin_val[-1::-1]

   # count all set bit '1' starting from index l-1
   print(len([bin_val[i] for i in range(l - 1, r) if bin_val[i] == '1']))

SetBits_cnt(83,1,6)

Output

Running the above code gives us the following result −

1010011
3

Using bitwise

The bitwise operator can also be used to get the setbits. In the below example we first apply the bitwise operator taking the range into consideration and then pass it on to another function which counts only the set bits.

Example

 Live Demo

def trackBitsInRange(n, l, r):
   # using bitwise operator
   bit_num = ((1 << r) - 1) ^ ((1 << (l - 1)) - 1)
   # After bitwise operation count the set bits
   return trackSetBits(n & bit_num)

def trackSetBits(n):
   count = 0
   while (n):
      n &= (n - 1)
      count = count + 1
   return count

print(trackBitsInRange(83,1,6))

Output

Running the above code gives us the following result −

3

Updated on: 12-Jan-2021

166 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements