Created
July 20, 2017 04:50
-
-
Save rmunn/bc49d32a586cdfa5bcab1c3e7b45d7ac to your computer and use it in GitHub Desktop.
Bitcount (aka popcount) implementation in F#, for 32 and 64-bit ints
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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
See also https://stackoverflow.com/questions/109023/how-to-count-the-number-of-set-bits-in-a-32-bit-integer