Forums
New posts
Search forums
Members
Current visitors
Log in
Register
What's new
Search
Search
Search titles only
By:
New posts
Search forums
Menu
Log in
Register
Install the app
Install
Forums
Archive
Archive
C Programming
Bit count of an integer
JavaScript is disabled. For a better experience, please enable JavaScript in your browser before proceeding.
You are using an out of date browser. It may not display this or other websites correctly.
You should upgrade or use an
alternative browser
.
Reply to thread
Message
[QUOTE="Mark Bluemel, post: 3126016"] Leaving aside the problems of reading this code aloud (I used to be a trainer and I know the pitfalls of a variable called "cnt")... Why do we need so many shifts? You need (sizeof int) * CHAR_BITS shifts even if there are no bits set in i. At the least, this may be less wasteful... (untested) int bitcount(unsigned int i) /* don't you want it unsigned? */ { unsigned int cnt = 0; while(i) { cnt += i & 1; i >>= 1; } return cnt; } Seems equivalent to (but more verbose than) [URL]http://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetNaive[/URL] That webpage then looks at other techniques... [/QUOTE]
Verification
Post reply
Forums
Archive
Archive
C Programming
Bit count of an integer
Top