Add a working implementation of FindFirstSet + tests.

Signed-off-by: Adrian Conlon <Adrian.conlon@gmail.com>
This commit is contained in:
Adrian Conlon 2019-07-30 23:55:20 +01:00
parent fc84e05839
commit dedc340bf5
2 changed files with 40 additions and 8 deletions

View File

@ -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;
}
}
}

View File

@ -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);
}
}
}