Skip to main content

How to Count Binary Digit Occurrences in Python

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

# ⛔️ Incorrect: Counting on the raw bin() output includes the '0b' prefix
# '0b' contains a '0', which skews the zero count
raw_binary = bin(number)
print(f"Raw binary: {raw_binary}")
print(f"Incorrect Zero count: {raw_binary.count('0')}")

# ✅ Correct: Slice off the '0b' prefix first
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
note

This method works perfectly for positive integers. For negative numbers, bin(-5) returns '-0b101', so you might need to handle the negative sign index slicing differently if you are dealing with signed bit representations.

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

# ✅ Correct: Built-in method for counting 1s
ones_count = number.bit_count()

# To get zeros, we need the total bit length
# .bit_length() returns the number of bits required to represent the integer
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:
# ANDing n with n-1 flips the least significant 1-bit to 0
n &= (n - 1)
count += 1
return count

number = 29 # Binary: 11101

# ✅ Correct: Counting using bitwise logic
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

# Handle the case of 0 separately as it has 1 zero bit (conceptually)
if n == 0: return 1, 0

while n > 0:
if n & 1 == 1:
ones += 1
else:
zeros += 1
# Shift bits to the right
n >>= 1
return zeros, ones

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

Output:

Zeros: 3, Ones: 3
note

The iterative shift method counts significant zeros but stops once the number becomes 0. It naturally matches the length of the binary representation without leading zeros.

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.