Q:

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

belongs to collection: Java Basic Programs

0

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

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

 

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 swap the first and second bits of ... >>
<< Java program to determine the class of a given IP ...