Java program to check whether all bits of the number are UNSET (LOW)

Given/input an integer number, we have to check whether all bits of the number are UNSET (LOW).
Submitted by Nidhi, on March 06, 2022

Problem Solution:

In this program, we will read a number from the user and check all bits of input number are UNSET/LOW.

Program/Source Code:

The source code to check whether all bits of the number are UNSET/LOW is given below. The given program is compiled and executed successfully.

// Java program to check whether all bits 
// of the number are UNSET/LOW

import java.util.Scanner;

public class Main {
  static boolean isAllBitsUnset(byte num) {
    int loop, cnt = 0;

    for (loop = 7; loop >= 0; loop--) {
      //check, if there is any SET/HIGH bit
      if ((num & (1 << loop)) != 0) {
        cnt = 1;
        break;
      }
    }
    if (cnt == 0)
      return true;
    else
      return false;
  }

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

    System.out.printf("Enter an integer number (between 0-255): ");
    number = SC.nextByte();

    if (isAllBitsUnset(number))
      System.out.printf("All bits are UNSET/LOW.\n");
    else
      System.out.printf("All bits are not UNSET/LOW.\n");
  }
}

Output:

Enter an integer number (between 0-255): 4
All bits are not UNSET/LOW.

Explanation:

In the above program, we imported the "java.util.Scanner" package to read input from the user. And, created a public class Main. It contain two static methods isAllBitsUnset() and main().

The isAllBitsUnset() method is used to check all bits of a specified number are LOW or not and return a Boolean value to the calling method.

The main() method is an entry point for the program. Here, we read a number from the user using Scanner class and called isAllBitsUnset() method to check all bits of an input number is LOW or not and printed appropriate message.

Java Basic Programs »



Related Programs



Comments and Discussions!

Load comments ↻





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