Q:

Java program to check nth bit of 16-bit number is set or not

belongs to collection: Java Basic Programs

0

Java program to check nth bit of 16-bit number is set or not

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Program/Source Code:

The source code to check nth bit of the 16-bit number is set or not is given below. The given program is compiled and executed successfully.

// Java program to check nth bit of 
// 16-bit number is set or not

import java.util.Scanner;

public class Main {
  public static void main(String[] args) {
    Scanner SC = new Scanner(System.in);

    short n = 0;
    short k = 0;

    System.out.printf("Enter a 16 bit number: ");
    k = SC.nextShort();

    System.out.printf("Enter the bit number: ");
    n = SC.nextShort();

    if (n < 0 || n > 16) {
      System.out.printf("Enter between 0-15\n");
      return;
    }

    k = (short)(k >> n);

    if ((k & 1) == 1)
      System.out.printf("BIT number %d is set\n", n);
    else
      System.out.printf("BIT number %d is not set\n", n);
  }
}

Output:

Enter a 16 bit number: 9
Enter the bit number: 3
BIT number 3 is set

Explanation:

In the above program, we imported the "java.util.Scanner" package to read the variable's value from the user. And, created a public class Main. It contains a static method main().

 

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Java Basic Programs

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
Java program to check a number contains the altern... >>
<< Java program to check a given number is EVEN or OD...