junky_fellow said:
Can anybody suggest me an efficient way of counting
no. of 1's in an integer (assume size of int=4)?
Note: no looping is allowed.
i agree this is a homework question. i tried a lot
but couldn't find any solution.
Any hints will be highly appreciated.
thanx a ton...
Create a lookup table with 256 entries where each entry holds the number of
bits for each byte value (from 0 - 255):
/* Notice the recursive series pattern... */
/* Check out the first four entries, then every other entry, then every
fourth entry (see the pattern.?.) */
/* Another solution could make use of this pattern....!!! */
int bits_in_a_byte[256]={0,1,1,2, 1,2,2,3, 1,2,2,3, 2,3,3,4, 1,2,2,3 ,
2,3,3,4, 2,3,3,4, 3,4,4,5.etc..};
The for each byte in you 4 byte int you can do a lookup on this table and
add all the results together.
You can use casting of pointers to get each byte of the int as follows:
long value;
char byte1, byte2, byte3, byte4;
char *p;
p=(char *) &value;
byte1= p[0];
byte2=p[1];
byte3=p[2];
byte4=p[3];
This makes some assumptions about the sizeof long etc but I hope you get the
general gist...
Sean