In this article, we’ll be counting the number of bits set to one using Java. To make it more transparent, let’s take number 6 as an example. Number 6 is represented as 110 in binary. From our example, the output is 2, as there are two ones in the binary of the converted number. In this process, we use two concepts related to the binary numbers.

  • Binary Comparison
  • Binary Shifting

What is Binary Comparison?

In our example, we are using and operation (&) for the binary comparison. It also called as bitwise and operation. Let’s take a look at the below example to understand how this binary comparison works with & operator.

For Eg: Let’s take n as 4 and evaluate the (n&1) operation.

n = 00000000 00000100

1 = 00000000 00000001 AND
——————————
0 = 00000000 00000000

Logic Gate of AND operation

From the bitwise-and, result of (n&1); where n=4 is 0. This method is frequently used to extract the Least Significant Bit (LSB) from a given number.

What is Binary Shifting?

Binary shifting refers to as shifting of all the bits in the operand used to a particular direction assigned by the user. There are two types of shifting.

  • Arithmetic Left shifting(<<)
  • Arithmetic Right shifting(>>)

In our example, arithmetic Right shifting is used to shift all the bits to the right side. To understand how arithmetic right shifting works, take a look at the below example.

When n = 12    Binary Representation = 1100

Let’s apply right shifting to the 12 => 1100>>1 which shifts one bit to the right at a time.

1st Iteration – Last 0 is removed (110)
2nd Iteration – Next 0 is removed (11)

The code

public static int countBitsSetToOne(int number) { 
      int count = 0; 
      while (number > 0){ 
        //binary comparison
        count = count + (number & 1); 
        //binary shifting
        number = number >> 1; 
      } 
      return count; 
}

Now call the function from the main menu

public static void main(String args[]){ 
	System.out.print("Please enter the number: ");
	//take the input from the user
	Scanner input = new Scanner(System.in);
	int number = input.nextInt();
	        
	System.out.print("Total number of 1s
                            : "+countBitsSetToOne(number)); 
	//close the scanner instance
	input.close();
} 

Code Explanation

In here, we have created a static method which takes one integer parameter. First, it checks whether the number is equal to zero or not. If the number is equal to zero, it will return the default value of the count variable; which is zero. When the number is greater than zero, it will increase the count while doing the bitwise-and operation. As I said earlier, bitwise-and returns the LSB of a number. Finally, binary shifting is done to shift all the bits to the right one by one until the whole iteration ends. When the number becomes zero, while loop terminates and returns the count.

Result

Please enter the number: 7

Total number of 1s is: 3

Recomanded Reading

Last modified: March 18, 2019