0
What is this code actually representing ? If someone could please explain to me in details.
int bnum=0b1000001;//1001 -> 9 int count=0; while(bnum>0) { //System.out.println(bnum); if((bnum&1)==0) { count++; } bnum = bnum >> 1; } System.out.println("count="+count);
2 Answers
+ 3
int bnum=0b1000001;//this value 65 in binary format. stored in int variable as 65
int count=0;
while(bnum>0)
{
//System.out.println(bnum);
if((bnum&1)==0) // this checking number is even number by "bitwise logical and" & operator
{
count++;
}
bnum = bnum >> 1; // this right shifting value by 1 bit position
// ex : 10000001 => 01000000 = 32
}
System.out.println("count="+count); // how many even number found 5 => ( 32,16,8,4,2)
Hope it helps..
+ 2
Rakan Ezzedin this is a bit counter to determine the number of zero bits in the binary number. Notice the conditional (bnum&1)==0, which tests whether the lowest bit is zero by using the bitwise and (&) operator. When the bit is zero the counter increments.
The last line of the while loop shifts all bits of the binary number rightward by 1 bit. Then it can test the next bit for zero, as that bit has now shifted into the lowest position.
The loop continues until the highest 1 bit has been shifted out and bnum becomes zero. At the end it prints count, which is the number of zeros (excluding leading zeros).