Log In  
Log In  

Adapting a solution found ca. page 180 of this white paper:


I finagled it into this PICO-8-specific form, which counts every bit (including fractional bits) in constant and pretty-brief time:

function popcount(v)
  return band((band(v+v*.0625,0x0f0f.0f0f)*0x0101.0101)*256,255)

It's a bit uglier than it would be in C/C++, but it's mostly the same operations, with a minor adaptation for the 16-bit shifts inherent in 16.16 fixed-point multiplies.

Just leaving it here in case anyone ever needs it.

PS: Apparently it's commonly called "popcount" or "popcnt", after an SSE instruction that does it. Basically, it's the population-of-1's count. Had no idea it had a name.

P#49855 2018-03-02 03:29 ( Edited 2018-03-02 08:29)

[Please log in to post a comment]

About | Contact | Updates | Terms of Use
Follow Lexaloffle:        
Generated 2019-05-25 21:24 | 0.014s | 2097k | Q:9