Population Count Pattern
denvaar.devΒ·1d
πŸ”’Bit Manipulation
Preview
Report Post

Understanding why a concise, macro-defined array can be used as a lookup table for finding the number of set bits in a number.

2023-10-24

programming

I was looking at Sean Anderson’s β€œBit Twiddling Hacks” page. One method for counting set bits using a lookup table caught my attention.

Here’s a similar version, modified for completeness.

// https://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetTable

#include <stdlib.h>
#include <stdio.h>
#include <stdint.h>

#define B2(n) n, n+1, n+1, n+2
#define B4(n) B2(n), B2(n+1), B2(n+1), B2(n+2)
#define B6(n) B4(n), B4(n+1), B4(n+1), B4(n+2)

static const uint8_t table[256] = {
B6(0), B6(1), B6(1), B6(2)
};

#define BASE_10 10

int main(int argc, char *...

Similar Posts

Loading similar posts...

Keyboard Shortcuts

Navigation
Next / previous item
j/k
Open post
oorEnter
Preview post
v
Post Actions
Love post
a
Like post
l
Dislike post
d
Undo reaction
u
Recommendations
Add interest / feed
Enter
Not interested
x
Go to
Home
gh
Interests
gi
Feeds
gf
Likes
gl
History
gy
Changelog
gc
Settings
gs
Browse
gb
Search
/
General
Show this help
?
Submit feedback
!
Close modal / unfocus
Esc

Press ? anytime to show this help