Skip to content

How to Count Binary Digit Occurrences in Python

How to count 1s and 0s in a binary number using string methods, bitwise operations, and Python's bit_count(), with examples and tips for choosing the right approach.

In computer science and digital logic, counting the number of set bits (1s) and unset bits (0s) in a binary representation is a fundamental task. This is often referred to as calculating the Hamming Weight or Population Count for the 1s.

This guide explores efficient ways to count binary digits in Python, ranging from simple string manipulation to bitwise operations optimized for performance.

Understanding Binary Representation

In Python, integers are objects that can be represented as binary strings using the bin() function.

  • Decimal: 10
  • Binary: 0b1010 (Prefix 0b indicates binary)

When counting digits, we usually want to count the bits in the value (1010), ignoring the prefix (0b).

Method 1: String Manipulation (Easiest)

The most readable way to count digits is to convert the number to a binary string and use the standard string .count() method.

Basic Implementation

number = 42

raw_binary = bin(number)
print(f"Raw binary: {raw_binary}")
print(f"Incorrect Zero count: {raw_binary.count('0')}") 

binary_string = bin(number)[2:]
print(f"Clean binary: {binary_string}")

zeros = binary_string.count('0')
ones = binary_string.count('1')

print(f"Zeros: {zeros}")
print(f"Ones:  {ones}")

Output:

Raw binary: 0b101010
Incorrect Zero count: 4
Clean binary: 101010
Zeros: 3
Ones:  3

Method 2: Using int.bit_count() (Python 3.10+)

If you are using Python 3.10 or newer, integers have a built-in method specifically for counting set bits (1s). This is highly optimized and faster than string conversion.

number = 12345

ones_count = number.bit_count()

total_bits = number.bit_length()
zeros_count = total_bits - ones_count

print(f"Binary: {bin(number)}")
print(f"Ones:   {ones_count}")
print(f"Zeros:  {zeros_count}")

Output:

Binary: 0b11000000111001
Ones:   6
Zeros:  8

Method 3: Bitwise Operations (for Integers)

For algorithmic interviews or environments where string conversion overhead is too high, you can use bitwise operators. Brian Kernighan's algorithm is a famous way to count set bits (1s) efficiently.

Brian Kernighan's Algorithm

This algorithm jumps through the 1s only, rather than iterating through every bit position.

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

number = 29 # Binary: 11101

ones = count_set_bits(number)
print(f"Set bits (1s) in {number}: {ones}")

Output:

Set bits (1s) in 29: 4

Shifting for Zeros and Ones

A simpler approach iterates through every bit using the right shift operator >>.

def count_bits_iterative(n):
    zeros = 0
    ones = 0
    
    if n == 0: return 1, 0

    while n > 0:
        if n & 1 == 1:
            ones += 1
        else:
            zeros += 1
        n >>= 1
    return zeros, ones

z, o = count_bits_iterative(42) # 101010
print(f"Zeros: {z}, Ones: {o}")

Output:

Zeros: 3, Ones: 3

Conclusion

To count binary digits in Python:

  1. Use bin(n)[2:].count('1') for the simplest, most readable solution involving strings.
  2. Use n.bit_count() (Python 3.10+) for the fastest performance when counting 1s.
  3. Use n.bit_length() - n.bit_count() to derive the count of zeros efficiently.
Navigation