PopCountメソッドは、立っている(1
である)ビットの数(population count)を計上します。 x86 POPCNT命令に類似する演算を行います。
PopCountメソッドは、uint
/UInteger
, ulong
/ULong
の整数型のみに対して定義されています。 なお、結果はint
/Integer
で返されます。
BitOperations.PopCountメソッドで立っているビットの数を計上する .NET Core 3.0
Imports System
Imports System.Numerics
Module Sample
Sub Main()
' BitOperations.PopCountメソッドメソッドはUInteger/ULongに対してのみ使用できる
Dim val As UInteger = &B_0000_0000_0000_0001_1000_0000_0000_0000UI
' BitOperations.PopCountで立っているビット(1のビット)の数を求める
Dim popcnt As Integer = BitOperations.PopCount(val)
For Each _val As UInteger In New UInteger() {&H1UI, &H5UI, &H123UI, &HCAFEUI, &HFFFFFFFEUI}
popcnt = BitOperations.PopCount(_val)
Console.WriteLine($"PopCount({_val.ToBinary()}) = {popcnt}")
Next
End Sub
#Region "数値を二進数表記で文字列化するためのメソッド"
<System.Runtime.CompilerServices.Extension> _
Function ToBinary(ByVal number As UInteger) As String
Return "&B_" + Convert.ToString(number, 2).PadLeft(8 * Len(number), "0"c)
End Function
#End Region
End Module
実行結果
PopCount(&B_00000000000000000000000000000001) = 1 PopCount(&B_00000000000000000000000000000101) = 2 PopCount(&B_00000000000000000000000100100011) = 4 PopCount(&B_00000000000000001100101011111110) = 11 PopCount(&B_11111111111111111111111111111110) = 31