Java program to find the number of bits required to represent a number

Given/input a number, we have to find the number of bits required to represent it.
Submitted by Nidhi, on March 06, 2022

Problem Solution:

In this program, we will read an integer number and find the number of bits required to represent the number.

Program/Source Code:

The source code to find the number of bits required to represent a number is given below. The given program is compiled and executed successfully.

// Java program to find the number of bits 
// required to represent a number

import java.util.Scanner;

public class Main {
  static int countBit(int n) {
    int count = 0, i;

    if (n == 0)
      return 0;

    for (i = 0; i < 32; i++) {
      if (((1 << i) & n) != 0)
        count = i;
    }
    return ++count;
  }

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

    int num = 0;

    System.out.printf("Enter an integer number: ");
    num = SC.nextInt();

    System.out.printf("Total number of bits required: %d\n", countBit(num));
  }
}

Output:

Enter an integer number: 255
Total number of bits required: 8

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 countBit() and main().

The countBit() method is used to find the total number of bits required to represent the specified number and return the result to the calling function.

The main() method is an entry point for the program. Here, we read an integer number from the user using the Scanner class and called the countBit() method to get the total number of bits required. After that, we printed the result.

Java Basic Programs »



Related Programs



Comments and Discussions!

Load comments ↻





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