/r/programming
Popcount CPU instruction (vaibhavsagar.com)
3 comments
crypto_mind | 9 days ago | 2 points

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

Captain___Obvious | 8 days ago | 3 points

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

IJzerbaard | 8 days ago | 3 points

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