Click to See Complete Forum and Search --> : no. of Bit set in any number


yuwaraj
October 21st, 2004, 08:11 AM
Hi All,
If i have to find how may bits are set in any given number ,for this i have found one pattern
i.e.
2 = 2^1 = 1
4 = 2^2 = 1
5 = 2^2+1 = 2
6 = 2^2+2^1 = 2
.
.
11 = 2^3+2^1+1 = 3
.
.
19= 2^4+2^1+1 =3
so on

First thing i am not sure whether this method is appropriate or not , if yes then to implement
it i have to keep on dividing with highest power of 2 (two) which is minimum than given no. , and continue
with the process with remender till my remender is 1 .
But then real problem is how do i know what is highest power of 2 which is less than this given
number.If any other method please let me know.

Thanx in advance

mehdi62b
October 21st, 2004, 09:46 AM
Hi,

Take a look at my code,

int n=;//Get it from user

int s=0;

while(n!=0)

{

if(n%2==1)s++;

n/=2;

}
return s;//s is the result

HtH.

yuwaraj
October 25th, 2004, 01:27 AM
Hi mehandi62b,
Thanx for the quick reply. The solution you sent is exactly what i wanted .
Thanx once again.
Yuwaraj

silvercl
October 25th, 2004, 06:21 AM
Hi mehandi62b and yuwaraj,
please look at this optimised code, less computations (even though the same by mehandi62b)


int n=;//Get it from user

int s=0;

while(n!=0)
{

if (n & 1) s++; //if(n%2==1)s++;

n>>=1; //n/=2;

}
return s;//s is the result


Now, this is also the same, but just compact coding,

int n=;//Get it from user

int s=0;

while( s+= (n&1), n>>=1 );

return s;

This can help in macro-ing this code (I mean wrtting a macro for this purpose).

-SilverZ.

yuwaraj
October 26th, 2004, 03:45 AM
Hi,
Thanx silverZ ,
This is cool way to programe as i am clear abt the logic send by mehandi62b .

thanx both of u.

MrViggy
October 26th, 2004, 12:14 PM
There are faster methods. Check out:

http://www-db.stanford.edu/~manku/bitcount/bitcount.html

:cool:

Viggy