I need C code to return the number of 1's in an unsigned char in C. I need an explanation as to why it works if it's not obvious. I've found a lot of code for a 32-bit number but not much for an unsigned char.
相关问题
- Multiple sockets for clients to connect to
- What is the best way to do a search in a large fil
- glDrawElements only draws half a quad
- Index of single bit in long integer (in C) [duplic
- Equivalent of std::pair in C
HACKMEM has this algorithm in 3 operations (roughly translated to C):
(
ULL
is to force 64-bit arithmetic. It's needed, just barely... this calculation requires 33-bit integers.)Actually, you can replace the second constant with
042104210021ULL
, since you're only counting 8 bits, but it doesn't look as nicely symmetrical.How does this work? Think of
c
bit-wise, and remember that(a + b) % c = (a % c + b % c) % c
, and(a | b) == a + b
iff(a & b) == 0
.If you don't have 64-bit arithmetic available, you can split
c
up into nibbles and do each half, taking 9 operations. This only requires 13 bits, so using 16- or 32-bit arithmetic will work.For example, if
c == 105 == 0b11001001
,The same code will work for an unsigned char. Loop over all bits testing them. See this.
an unsigned char is a "number" in just the same way that a 32-bit float or integer is a "number", what the compiler deems them to represent is what changes.
if you picture a char as its bits:
01010011 (8 bits);
you can count the set bits by doing the following:
take the value, lets say x, and take x % 2, the remainder will be either 1 or 0. that is, depending on the endianness of the char, the left or right most bit. accumulate the remainder in a separate variable (this will be the resulting number of set bits).
then >> (right shift) 1 bit.
repeat until 8 bits have been shifted.
the c code should be pretty simple to implement from my pseudocode, but basically
As already answered, the standard ways of counting bits also work on unsigned chars.
Example:
For a integer as small as an unsigned char you get best performance using a small lookup-table.
I know what population-count algorithms you're mentioning. They work by doing arithmetic of multiple words smaller than an integer stored in a register.
This technique is called SWAR (http://en.wikipedia.org/wiki/SWAR).
For more information I suggest you check out the hackers delight website: www.hackersdelight.org. He has example code and written a book that explains these tricks in detail.
Have an array that knows the number of bits for 0 through 15. Add the results for each nibble.