When given a number ,n
, we check if the 4th bit of n
is set using the right shift operator.
Example 1:
Example 1:
The solution is straightforward.
AND
operator on the bit mask and the given number to check if the fourth bit was set or not.We can use the left shift operator to generate the bit mask. 1000
is the bit mask we are looking for, and it can be generated using the following expression.
1 << 3
AND
operationBitwise AND
is performed on the given number and the bit mask. If the resulting number is zero, it means the 4th bit is unset. Otherwise, the 4th bit is set.
Example:
Consider n=10 (1010)
As n & mask
is greater than zero, the 4th bit is set.
mask
.n
.n & mask
to check whether the 4th bit is set or unset.