From dedc340bf5c5955e8c10365d81335ba72d71d73d Mon Sep 17 00:00:00 2001 From: Adrian Conlon Date: Tue, 30 Jul 2019 23:55:20 +0100 Subject: [PATCH] Add a working implementation of FindFirstSet + tests. Signed-off-by: Adrian Conlon --- EightBit/Chip.cs | 20 +++++++++------- EightBit/EightBit.UnitTest/ChipUnitTest.cs | 28 ++++++++++++++++++++++ 2 files changed, 40 insertions(+), 8 deletions(-) diff --git a/EightBit/Chip.cs b/EightBit/Chip.cs index ea4460a..9872621 100644 --- a/EightBit/Chip.cs +++ b/EightBit/Chip.cs @@ -72,18 +72,22 @@ namespace EightBit public static bool EvenParity(byte value) => EvenParity((int)value); - public static int FindFirstSet(int value) + public static int FindFirstSet(int x) { - var bits = new BitVector32(value); - for (var i = 31; i >= 0; --i) + if (x == 0) { - if (bits[i]) - { - return i - 1; - } + return 0; } - return 0; + var t = 1; + var r = 1; + while ((x & t) == 0) + { + t <<= 1; + ++r; + } + + return r; } } } diff --git a/EightBit/EightBit.UnitTest/ChipUnitTest.cs b/EightBit/EightBit.UnitTest/ChipUnitTest.cs index 44f60cc..f12ab51 100644 --- a/EightBit/EightBit.UnitTest/ChipUnitTest.cs +++ b/EightBit/EightBit.UnitTest/ChipUnitTest.cs @@ -191,5 +191,33 @@ namespace EightBit var word = Chip.MakeWord(0xcd, 0xab); Assert.AreEqual(0xabcd, word); } + + [TestMethod] + public void TestFindFirstSet_1() + { + var position = Chip.FindFirstSet(12); + Assert.AreEqual(3, position); + } + + [TestMethod] + public void TestFindFirstSet_2() + { + var position = Chip.FindFirstSet(1); + Assert.AreEqual(1, position); + } + + [TestMethod] + public void TestFindFirstSet_3() + { + var position = Chip.FindFirstSet(128); + Assert.AreEqual(8, position); + } + + [TestMethod] + public void TestFindFirstSet_4() + { + var position = Chip.FindFirstSet(0); + Assert.AreEqual(0, position); + } } }