×

Java Programs

Java Practice

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

Given/input a short integer (i.e., 16-bit number), we have to check its nth bit is set or not.
Submitted by Nidhi, on March 10, 2022

Problem statement

In this program, we will read a 16-bit integer number from the user. Then we will check nth bit of the 16-bit number is set or not.

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

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().

The main() method is an entry point for the program. Here, we read a 16-bit integer and bit number from the user using Scanner class and checked bit number of the given number is HIGH or not and printed the appropriate message.

Java Basic Programs »



Related Programs



Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.