Org.BouncyCastle.Math.BigInteger.GetLowestSetBit C# (CSharp) Method

GetLowestSetBit() public method

public GetLowestSetBit ( ) : int
return int
		public int GetLowestSetBit()
		{
			if (this.sign == 0)
				return -1;

			int w = magnitude.Length;

			while (--w > 0)
			{
				if (magnitude[w] != 0)
					break;
			}

			int word = (int) magnitude[w];
			Debug.Assert(word != 0);

			int b = (word & 0x0000FFFF) == 0
				?	(word & 0x00FF0000) == 0
					?	7
					:	15
				:	(word & 0x000000FF) == 0
					?	23
					:	31;

			while (b > 0)
			{
				if ((word << b) == int.MinValue)
					break;

				b--;
			}

			return ((magnitude.Length - w) * 32 - (b + 1));
		}

Usage Example

Example #1
0
		public void TestGetLowestSetBit()
		{
			for (int i = 0; i < 10; ++i)
			{
				BigInteger test = new BigInteger(128, 0, random).Add(one);
				int bit1 = test.GetLowestSetBit();
				Assert.AreEqual(test, test.ShiftRight(bit1).ShiftLeft(bit1));
				int bit2 = test.ShiftLeft(i + 1).GetLowestSetBit();
				Assert.AreEqual(i + 1, bit2 - bit1);
				int bit3 = test.ShiftLeft(13 * i + 1).GetLowestSetBit();
				Assert.AreEqual(13 * i + 1, bit3 - bit1);
			}
		}