Java program to count total bits in a number

Java 8Object Oriented ProgrammingProgramming

The total bits in a number can be counted by using its binary representation. An example of this is given as follows −

Number = 9
Binary representation = 1001
Total bits = 4

A program that demonstrates this is given as follows.

Example

Live Demo

public class Example {
   public static void main(String[] arg) {
      int num = 10;
      int n = num;
      int count = 0;
      while (num != 0) {
         count++;
         num >>= 1;
      } 
      System.out.print("The total bits in " + n + " are " + count);
   }
}

Output

The total bits in 10 are 4

Now let us understand the above program.

First, the number is defined. Then the total bits in the number are stored in count. This is done by using the right shift operator in a while loop. Finally, the total bits are displayed. The code snippet that demonstrates this is given as follows −

int num = 10;
int n = num;
int count = 0;
while (num != 0) {
   count++;
   num >>= 1;
}
System.out.print("The total bits in " + n + " are " + count);
raja
Published on 05-Dec-2018 16:25:37
Advertisements