
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Check if all bits of a number are set in Python
In computers, data is stored in the binary form, which uses the two digits 0 and 1. Each digit in this format is known as a bit.
In this article, we are going to check if all bits of a number are set in Python. A bit is said to be set if the binary representation of every bit is 1.
Let's look at some scenarios to understand this better:
Scenario 1
Input: 3 Binary: 111 Output: True Explanation: All bits are 1.
Scenario 2
Input: 6 Binary: 110 Output: False Explanation: Not all bits are 1.
Checking if the Bits are set using Python
To check whether all the bits in a number are set to 1, we can use a mathematical pattern. Such numbers are always of the form 2n - 1, where n is a positive integer.
This is because subtracting 1 from a power of 2 results in a binary number where all the lower n bits are set to 1. For example:
2^1 - 1 = 1 -> Binary: 0b1 2^2 - 1 = 3 -> Binary: 0b11 2^3- 1 = 7 -> Binary: 0b111
Let's dive into the examples:
Example 1
In the following example, we are going to consider the input as 3 and check whether the bits are set:
def demo(n): return n != 0 and ((n + 1) & n) == 0 x = 3 result = demo(x) print(f"Input: {x}") print(f"Binary: {bin(x)[2:]}") print(f"All Bits Set: {result}")
Following is the output of the above program:
Input: 3 Binary: 11 All Bits Set: True
Example 2
Following another example, where we are going to take the input as 6 and check whether the bits are set:
def demo(n): return n != 0 and ((n + 1) & n) == 0 x = 6 result = demo(x) print(f"Input: {x}") print(f"Binary: {bin(x)[2:]}") print(f"All Bits Set: {result}")
If we run the above program, it will generate the following output:
Input: 6 Binary: 110 All Bits Set: False
Conclusion
To check if all the bits of a number are set in Python, we can use a simple bit-wise trick (n & (n + 1)) == 0. These work perfectly for numbers like 1, 3, 5, 7, etc., where all bits in their binary form are 1.