Home
Insert
Update snippet 'Count set bits in a bigint and a BitArray'
Title
Description
Count the number of bits in a bigint (System.Numerics.BigInteger) and a BitArray. Note that version 4 is the fastest.
Source code
open System.Linq let bitcount (b:bigint) = let mutable b = b let mutable count = 0 while b <> bigint 0 do b <- b &&& (b-(bigint 1)) count <- count + 1 count let bitcount2 (b:System.Collections.BitArray) = (b:> System.Collections.IEnumerable).Cast<bool>() |> Seq.map (fun v -> if v then 1 else 0) |> Seq.sum let bitcount3 (b:System.Collections.BitArray) = let mutable count = 0 for bit in b do if bit then count <- count+1 count let bitcount4 (b:System.Collections.BitArray) = let mutable count = 0 for bit=0 to b.Length-1 do if b.Get(bit) then count <- count+1 count
Tags
bigint
bits
bit manipulation
bitarray
bigint
bits
bit manipulation
bitarray
Author
Link
Reference NuGet packages
If your snippet has external dependencies, enter the names of NuGet packages to reference, separated by a comma (
#r
directives are not required).
Update