Skip to content

Fix bug with BigInteger.TrailingZeroCount (#77727) #78174

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Nov 11, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -3481,42 +3481,19 @@ public static BigInteger TrailingZeroCount(BigInteger value)

ulong result = 0;

if (value._sign >= 0)
{
// When the value is positive, we simply need to do a tzcnt for all bits until we find one set

uint part = value._bits[0];
// Both positive values and their two's-complement negative representation will share the same TrailingZeroCount,
// so the sign of value does not matter and both cases can be handled in the same way

for (int i = 1; (part == 0) && (i < value._bits.Length); i++)
{
part = value._bits[i];
result += (sizeof(uint) * 8);
uint part = value._bits[0];

i++;
}

result += uint.TrailingZeroCount(part);
}
else
for (int i = 1; (part == 0) && (i < value._bits.Length); i++)
{
// When the value is negative, we need to tzcnt the two's complement representation
// We'll do this "inline" to avoid needing to unnecessarily allocate.

uint part = ~value._bits[0] + 1;

for (int i = 1; (part == 0) && (i < value._bits.Length); i++)
{
// Simply process bits, adding the carry while the previous value is zero

part = ~value._bits[i] + 1;
result += (sizeof(uint) * 8);

i++;
}

result += uint.TrailingZeroCount(part);
part = value._bits[i];
result += (sizeof(uint) * 8);
}

result += uint.TrailingZeroCount(part);

return result;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -366,6 +366,9 @@ public static void TrailingZeroCountTest()

Assert.Equal((BigInteger)63, BinaryIntegerHelper<BigInteger>.TrailingZeroCount(Int64MaxValuePlusOne));
Assert.Equal((BigInteger)0, BinaryIntegerHelper<BigInteger>.TrailingZeroCount(UInt64MaxValue));

Assert.Equal((BigInteger)1000, BinaryIntegerHelper<BigInteger>.TrailingZeroCount(BigInteger.Pow(2, 1000)));
Assert.Equal((BigInteger)1000, BinaryIntegerHelper<BigInteger>.TrailingZeroCount(-BigInteger.Pow(2, 1000)));
}

[Fact]
Expand Down