- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies

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

# 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

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

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

- Related Articles
- 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++
- Count set bits using Python List comprehension
- Copy set bits in a range in C++
- Python Program to Count set bits in an integer
- Program to count total number of set bits of all numbers in range 0 to n in Python
- Check if bits of a number has count of consecutive set bits in increasing order 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?
- Python program to count total set bits in all number from 1 to n.
- C/C++ Program to Count set bits in an integer?
- Golang Program to count the set bits in an integer.