C/logic

Advertisement


Question
following program gives how many number of ones present in binary form of one number.
but i don't know what kind of logic used in this program because it's not my code.
 int CountBits (unsigned int x )  
{
static unsigned int mask[] = { 0x55555555,          0x33333333,          0x0F0F0F0F,          0x00FF00FF,          0x0000FFFF} ;

         int i ;   
      int shift ; /* Number of positions to shift to right*/
  for ( i =0, shift =1; i < 5; i ++, shift *=2)
 x = (x & mask[i ])+ ( ( x >> shift) & mask[i]);          return x;
}

Answer
This program is using the bitwise operators and using them to mask of specific bits to get to the solution.
I will not dive down to explain what it is doing.

The best way to understand any code is like this:
Simulate the program by hand and write down the value to watch in each step.
So, give different inputs and see what happens.
By making this, you must be able to understand the logic.

C

All Answers


Answers by Expert:


Ask Experts

Volunteer


Narendra

Expertise

I can answer questions in C related to programming, data structures, pointers and file manipulation. I use Solaris for doing C code and if you have questions related to C programming on Solaris, I will be able to help better.

Experience

6.5

Organizations belong to
Sun Microsystems

Awards and Honors
Brain Bench Certified Expert C programmer.
Advanced System Software Certified

©2012 About.com, a part of The New York Times Company. All rights reserved.