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
See the bit twiddling hacks page: http://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetKernighan
there are many good solutions for this.
Also, this function in its simplest implementation is fairly trivial. You should take the time to learn how to do this.
base on Ephemient's post, we have the no branched 8 bits version. It is in hexadecimal expression.
Apply it twice, we have a 16bits version, which needs 9 operations.
Here I write a variant 16bits version which needs 64bits registers and 11 operations. It seems not better than the previous one, but it just uses 1 modulo operation.