Q:

Java program to count total HIGH bits of the given number

belongs to collection: Java Basic Programs

0

Java program to count total HIGH bits of the given 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 count the total HIGH bits of the given number is given below. The given program is compiled and executed successfully.

// Java program to count total HIGH bits 
// of the given number

import java.util.Scanner;

public class Main {
  static int countHighBits(short num) {
    byte i;
    int count = 0;

    for (i = 0; i < 16; i++) {
      if ((num & (1 << i)) != 0)
        count++;
    }

    return count;
  }

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

    short num = 0;

    System.out.printf("Enter number: ");
    num = SC.nextShort();

    System.out.printf("\nTotal HIGH bits are : %d\n", countHighBits(num));
  }
}

Output:

Enter number: 7

Total HIGH bits are : 3

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

The countHighBits() method is used to count the total HIGH bits of a given short integer using bitwise operators and return the result to the calling method.

 

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 reverse bits of the given number... >>
<< Java program to check whether all bits of the numb...