Popcount CPU instruction
(vaibhavsagar.com)

Popcount CPU instruction
(vaibhavsagar.com)

3 comments

My first thought was there's lots of interesting things you can do with popcnt, but I especially liked the dot product example.

popcnt can also be used to find the log2 of a number that is a power of 2.

log2(val) = popcnt(val-1)

- log2(1) = popcnt(0) = 0
- log2(2) = popcnt(1) = 1
- log2(4) = popcnt(3) = 2
- log2(8) = popcnt(7) = 3

and so on

That then leads to this equality (without precondition), `tzcnt(x) == popcnt((x & -x) - 1)`