diff options
Diffstat (limited to 'crypto/test/src/util/utiltest/IntegersTest.cs')
-rw-r--r-- | crypto/test/src/util/utiltest/IntegersTest.cs | 33 |
1 files changed, 33 insertions, 0 deletions
diff --git a/crypto/test/src/util/utiltest/IntegersTest.cs b/crypto/test/src/util/utiltest/IntegersTest.cs index a661144db..91c0bf2b6 100644 --- a/crypto/test/src/util/utiltest/IntegersTest.cs +++ b/crypto/test/src/util/utiltest/IntegersTest.cs @@ -32,5 +32,38 @@ namespace Org.BouncyCastle.Utilities.UtilTests Assert.AreEqual(31, Integers.NumberOfTrailingZeros(int.MinValue)); Assert.AreEqual(32, Integers.NumberOfTrailingZeros(0)); } + + [Test] + public void TestPopCount() + { + Random random = new Random(); + + for (int pos = 0; pos <= 24; ++pos) + { + int seed = Integers.RotateLeft(random.Next(0xFFFFFF) << 8, pos); + ImplTestPopCountRange(seed, pos, 0xFF); + } + } + + private static void ImplTestPopCountRange(int seed, int pos, int count) + { + for (int i = 0; i < count; ++i) + { + int n = seed + (i << pos); + int expected = SimpleBitCount(n); + Assert.AreEqual(expected, Integers.PopCount(n)); + Assert.AreEqual(expected, Integers.PopCount((uint)n)); + } + } + + private static int SimpleBitCount(int n) + { + int count = 0; + for (int i = 0; i < 32; ++i) + { + count += (n >> i) & 1; + } + return count; + } } } |