C code to count the number of '1' bits in an unsigned char

前端 未结 8 1746
孤街浪徒
孤街浪徒 2020-12-19 04:24

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 nu

8条回答
  •  粉色の甜心
    2020-12-19 05:08

    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.

提交回复
热议问题