Check the whether the kth bit from right is SET ?
In this blog post, we’ll explore how to check whether the k-th bit (from the right) of a number is set (i.e., is equal to 1) using bitwise operations in Python. This is a common problem that’s useful in programming challenges and low-level bit manipulation.
Problem Explanation
We are given a number
n
in its binary form and an integerk
, which indicates the position of the bit we want to check, starting from the right (with the least significant bit being the 1st bit). The goal is to determine whether the bit at positionk
is set (i.e., 1) or not set (i.e., 0).Example Walkthrough
Let’s take an example to clarify the concept. Suppose we have the number
n = 6
, which is110
in binary. Now, we want to check if the 1st bit from the right is set.
Convert the number to binary:
- The binary representation of
6
is110
.Identify the bit position:
- We want to check the 1st bit from the right.
Bitwise AND Operation:
- To check if the k-th bit is set, we perform a bitwise AND between the number
n
and1
shifted left(k - 1)
positions. This is done using the expression:- If the result is non-zero, the k-th bit is set; otherwise, it is not set.
Example 1: Check the 1st Bit in 6
- Binary of 6:
110
- We are checking the 1st bit:
- Perform the AND operation:
- Since the result is non-zero (
001
), the 1st bit is set.Example 2: Check the 2nd Bit in 6
- Binary of 6:
110
- We are checking the 2nd bit:
- Perform the AND operation:
- Since the result is non-zero (
010
), the 2nd bit is set.Example 3: Check the 3rd Bit in 6
- Binary of 6:
110
- We are checking the 3rd bit:
- Perform the AND operation:
- Since the result is non-zero (
100
), the 3rd bit is set.Now that we understand the concept, let’s write the Python code to implement this.
Python Code
How the Code Works
Input Handling: The user is prompted to input a number
n
and the bit positionk
they want to check.Binary Representation: The binary representation of the number is printed for clarity, using Python’s
bin()
function, which converts a number into its binary format.Checking the k-th Bit: The function
kthbit()
checks whether the bit at positionk
from the right is set or not by using the bitwise AND operation between the numbern
and the result of1 << (k - 1)
.Output:
- If the bit is set, the program outputs "SET".
- If the bit is not set, it outputs "NOT SET".
Example Input and Output
Input:
Output:
Input:
Output:
Input:
Output:
Conclusion
By using bitwise operations, specifically the left shift (
<<
) and bitwise AND (&
), we can efficiently check whether the k-th bit of a number is set. This method works in constant time and is a common technique in low-level programming, competitive programming, and situations where bit manipulation is necessary.This approach is both simple and powerful, allowing you to quickly analyze bits in a number and perform operations like checking, setting, or flipping bits.
Comments
Post a Comment