Write Java program to Count the total HIGH bits in the given number


The program prompts the user to input an integer and then counts the number of high bits (bits with a value of 1) in the binary representation of that integer.

Here's how the program works:

  • It prompts the user to enter an integer using System.out.printf() and Scanner class.
  • The input integer is stored in the variable num.
  • It sets the variable tot to 0 to count the number of high bits.
  • It enters a loop where it shifts the bits of the integer to the right by one position using the >> operator.
  • For each iteration of the loop, it checks the least significant bit of the integer using the bitwise AND operator &. If the least significant bit is 1, it increments the tot variable by 1.
  • The loop continues until the integer becomes 0.
  • Finally, it prints the total count of high bits using System.out.println().

Source Code

import java.util.Scanner;
public class Count_HighBits
{
	public static void main(String[] args)
	{
		Scanner input = new Scanner(System.in);
 
		int num = 0;
		int tot = 0;
 
		System.out.printf("Enter the Number : ");
		num = input.nextInt();
 
		while (num != 0)
		{
			if ((num & 1) == 1)
			{
				tot++;
			}
			num = num >> 1;
		}
		System.out.println("Number of HIGH Bits are : "+tot);
	}
}

Output

Enter the Number : 10
Number of HIGH Bits are : 2

Example Programs