How to count number of 1's in a 32 bit integer (do not loop throught the bits).
thanx
krithi
How to count number of 1's in a 32 bit integer (do not loop throught the bits).
thanx
krithi
well then how do you intend to do it? every method i can think of is, in one way or another, looping through the bits.Originally posted by krithi
(do not loop throught the bits).
hello, internet!
hmmm heres a loop through the bits method...
without looping through the bits im not so sure. Lookup tables will work but thats a hell of a lot more work.Code:#include <stdio.h> int main() { int value=0x1234;// any number will do int count=0; // set bits int i; for(i=0;i<32;i++) if ((value<<i)&1) ++count; printf("Number of set bits is %d\n",count); return 0; }
Free the weed!! Class B to class C is not good enough!!
And the FAQ is here :- http://faq.cprogramming.com/cgi-bin/smartfaq.cgi
>How to count number of 1's in a 32 bit integer (do not loop throught the bits).
Perhaps you're looking for this well known bit fiddling snippet?
-PreludeCode:unsigned countbits32_no_loop ( unsigned x ) { x = ( 0x55555555 & x ) + ( 0x55555555 & ( x >> 1 ) ); x = ( 0x33333333 & x ) + ( 0x33333333 & ( x >> 2 ) ); x = ( 0x0f0f0f0f & x ) + ( 0x0f0f0f0f & ( x >> 4 ) ); x = ( 0x00ff00ff & x ) + ( 0x00ff00ff & ( x >> 8 ) ); x = ( 0x0000ffff & x ) + ( 0x0000ffff & ( x >> 16 ) ); return x; }
My best code is written with the delete key.
I think id loop thru the bits.Why would you not want to? Salems look up table of 256 is workable but you would still need some calculations done adding the four bytes set bit counts together.
Preludes example tho clever is a maintainence programmers nightmare with hex numbers and shifts and no comments to help you see what the original programmer intended.It is not really self-documenting so should be commented.
Free the weed!! Class B to class C is not good enough!!
And the FAQ is here :- http://faq.cprogramming.com/cgi-bin/smartfaq.cgi