Skip to content

Instantly share code, notes, and snippets.

@rmunn
Created July 20, 2017 04:50
Show Gist options
  • Save rmunn/bc49d32a586cdfa5bcab1c3e7b45d7ac to your computer and use it in GitHub Desktop.
Save rmunn/bc49d32a586cdfa5bcab1c3e7b45d7ac to your computer and use it in GitHub Desktop.
Bitcount (aka popcount) implementation in F#, for 32 and 64-bit ints
let bitcount (n : int) =
let count2 = n - ((n >>> 1) &&& 0x55555555)
let count4 = (count2 &&& 0x33333333) + ((count2 >>> 2) &&& 0x33333333)
let count8 = (count4 + (count4 >>> 4)) &&& 0x0f0f0f0f
(count8 * 0x01010101) >>> 24
let bitcount64 (n : int64) =
let count2 = n - ((n >>> 1) &&& 0x5555555555555555L)
let count4 = (count2 &&& 0x3333333333333333L) + ((count2 >>> 2) &&& 0x3333333333333333L)
let count8 = (count4 + (count4 >>> 4)) &&& 0x0f0f0f0f0f0f0f0fL
(count8 * 0x0101010101010101L) >>> 56 |> int
bitcount -1 // Result: 32
bitcount64 (-1L) // Result: 64
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment