- Related Questions & Answers
- Count set bits in a range in C++
- Python program to count unset bits in a range.
- Count unset bits in a range in C++
- Copy set bits in a range in C++
- Count set bits using Python List comprehension
- Python Program to Count set bits in an integer
- Check if bits of a number has count of consecutive set bits in increasing order in Python
- Program to count total number of set bits of all numbers in range 0 to n in Python
- Count set bits in an integer in C++
- C# program to count total set bits in a number
- Java Program to Count set bits in an integer
- How to count set bits in a floating point number in C?
- C/C++ Program to Count set bits in an integer?
- Golang Program to count the set bits in an integer.
- Write a python program to count total bits in a number?

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

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.

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.

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)

Running the above code gives us the following result −

1010011 3

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.

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))

Running the above code gives us the following result −

3

Advertisements