Understanding the Problem
We are given two integers:
n – a non-negative integer whose binary representation we need to inspect
i – the position (0-based) of the bit we want to check
The task is to determine whether the i-th bit in the binary form of n is set (equal to 1). Bit positions start from the rightmost bit as position 0.
If the i-th bit is set, return true. Otherwise, return false.
Step-by-Step Solution with Example
step 1: Understand the binary representation of the number
Let’s take an example: n = 13 and i = 2.
Binary representation of 13 is 1101 (from right to left, bits are at positions 3, 2, 1, 0).
So, bits are: [1][1][0][1]
Now we want to check if the 2nd bit (from right) is set (i.e., is it 1?).
step 2: Create a bitmask for the i-th bit
We left-shift 1 by i positions to create a mask.
int mask = 1 << i; // i = 2 → mask = 1 << 2 = 100 in binary = 4
step 3: Perform bitwise AND with the number
Now, use bitwise AND between n and mask:
int result = n & mask; // 13 & 4 = 1101 & 0100 = 0100 = 4
If result ≠ 0, then the bit is set.
step 4: Return the final answer
return result != 0; // true (since bit is set)
Therefore, the output is true, meaning the 2nd bit in 13 is set.
Edge Cases
- Case 1: i is 0 – You are checking the rightmost bit. Works the same way.
- Case 2: i is larger than number of bits in n – For example,
n = 3 (binary 11), i = 4. The result will be 0 because that bit does not exist, so answer will be false.
- Case 3: n is 0 – All bits are unset. No matter what
i is, the result is always false.
- Case 4: i is negative – Should be considered invalid input. In real implementations, we check
if (i < 0) and handle accordingly.
Comments
Loading comments...