Check if the 4th bit of a number is set using a shift operator

Problem statement

When given a number ,n, we check if the 4th bit of n is set using the right shift operator.

Example 1:

  • Input: n=15
  • Output: Yes

Example 1:

  • Input: n=4
  • Output: No

Solution

The solution is straightforward.

  • We create a bit mask where the fourth bit is set and all other bits are unset.
  • Then, we use the AND operator on the bit mask and the given number to check if the fourth bit was set or not.

Step 1: Bit mask

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

Step 2: Bitwise AND operation

Bitwise 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)

  • n = 1010
  • mask = 1000
  • n & mask = 1000

As n & mask is greater than zero, the 4th bit is set.

Code

public class Main {
public static void main(String[] args) {
int mask = 1 << 3;
int n = 4;
String res = (n & mask) == 0?"unset":"set";
System.out.println("4th bit of " + n + " is " + res);
}
}

Explanation

  • Line 4: We use the left shift operator to generate the bit mask, mask.
  • Line 5: We define n.
  • Line 6: We use the expression n & mask to check whether the 4th bit is set or unset.
  • Line 7: We print the result.

Free Resources