In this article, we’ll be
counting the number of bits set to one using Java. To make it clearer, let’s
take number 6 as an example. Number 6 is written as 1102 in binary.
From our example, we’ll get the output as 2, as there are 2 ones in the binary
of the converted number. In this process, we use 2 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 the & operator.
For Eg: Let’s take n as 4
and evaluate the (n&1) operation.
Logic Gate of AND
operation
|
A
|
B
|
Result
|
0
|
0
|
0
|
0
|
1
|
0
|
1
|
0
|
0
|
1
|
1
|
1
|
1 = 00000000 00000001 AND
------------------------------
0 = 00000000 00000000
==================
From the bitwise-and, result of (n&1); where
n=4 is 0. This 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 2 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 right at a time.
1st Iteration
– Last 0 is removed (110)
2nd Iteration
– Next 0 is removed (11)
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();
}
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;
}
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 the number passed in. Finally, binary shifting is done to shift all
the bits to right one by one until the whole iteration ends. When the number
becomes zero, while loop terminates and returns the count.
No comments:
Post a Comment