5 Best Ways to Check if All Bits of a Number are Set in Python

Rate this post

πŸ’‘ Problem Formulation: We often encounter the need to verify whether a binary representation of a number is composed of all 1s. This might be to ensure a certain mask is fully implemented, or to satisfy another bitwise precondition. An example input could be the number 7, which in binary is 0b111, and we would expect the output to confirm that all bits are indeed set.

Method 1: Left Shift and Subtract Approach

This method involves shifting the bits of number 1 to the left by the number of bits in the input number, then subtracting one, and performing a bitwise AND operation with the original number. If the result matches the original number, all bits are set.

Here’s an example:

def all_bits_set(num):
    # Compute 1 shifted left by the bit length of num and subtract 1
    all_set = (1 << num.bit_length()) - 1
    # Perform bitwise AND and compare with num
    return num & all_set == num

print(all_bits_set(7)) # Example number

Output: True

This code defines a function called all_bits_set that takes an integer and compares it against a generated number where all bits are set to 1, to the length of the input number. The logical AND comparison will be true only if all bits in the input are 1.

Method 2: Check for Power of Two Minus One

A number with all bits set is always a power of two minus one. Thus, we can add 1 to the number and check if the result is a power of two, which is true only if it has a single 1 bit.

Here’s an example:

def is_power_of_two_minus_one(num):
    return (num + 1) & num == 0 and num != 0

print(is_power_of_two_minus_one(7))  # Example number

Output: True

This method defines a function is_power_of_two_minus_one, which leverages the arithmetic property that a number with all bits set plus one will result in a number that is a power of two. The additional condition ensures that zero is not falsely detected as all bits set.

Method 3: Bitwise Not Equal to Zero

The bitwise NOT operation on a number with all bits set should yield zero. This method applies the bitwise NOT operator and checks if the result equals zero.

Here’s an example:

def all_bits_set_bitwise_not(num):
    return ~num == 0

print(all_bits_set_bitwise_not(7))  # Example number

Output: False

This snippet demonstrates a method that applies the concept of bitwise NOT. However, due to Python’s handling of negative numbers with a complementary representation, this method is incorrect and thus not appropriate for checking if all bits are set. It’s shown here for educational purposes.

Method 4: Using Bin Function and Str Count

Convert the number to a binary string using the bin() function and count if the number of ‘1’s in the binary representation is equal to the total length minus the ‘0b’ prefix.

Here’s an example:

def all_bits_set_bin_count(num):
    bin_repr = bin(num)[2:]  # Remove '0b' prefix
    return bin_repr.count('1') == len(bin_repr)

print(all_bits_set_bin_count(7))  # Example number

Output: True

This method uses Python’s built-in bin() function to convert the number into a binary string, and then counts the number of ‘1’s to ensure that they match the length of the string minus the ‘0b’ prefix, thus indicating all bits are set.

Bonus One-Liner Method 5: All Built-in Check

Python’s all-encompassing all() function is used to iterate over the binary representation of the number, checking that all characters are ‘1’s, thus confirming all bits are set.

Here’s an example:

print(all(c == '1' for c in bin(7)[2:]))  # Example number

Output: True

This elegant one-liner makes use of list comprehension and Python’s all() function to iterate through each character in the binary representation of the number (discounting the ‘0b’ prefix) and confirms that every character is ‘1’.


  • Method 1: Left Shift and Subtract Approach. Efficient and mathematically sound. It may be less intuitive to those not familiar with bitwise operations.
  • Method 2: Power of Two Minus One. A clever arithmetic check that is fast and reliable, with the caveat of an additional condition to exclude zero.
  • Method 3: Bitwise Not. Not suitable for Python due to the representation of negative numbers, demonstrates a common pitfall in bitwise operations.
  • Method 4: Using Bin Function and Str Count. Easy to understand, utilizes standard Python functions, but can be slower for large numbers due to string processing overhead.
  • Bonus Method 5: All Built-in Check. Short and readable, harnesses Python’s high-level abstractions, though may be less efficient for very large numbers.