Skip to content
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

Fix BigInteger parse hex strings on negative numbers #84792

Merged
merged 1 commit into from
May 10, 2023
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 @@ -466,6 +466,11 @@ private static ParsingStatus HexNumberToBigInteger(ref BigNumberBuffer number, o

Debug.Assert(partialDigitCount == 0 && bitsBufferPos == -1);

if (isNegative)
{
NumericsHelpers.DangerousMakeTwosComplement(bitsBuffer);
}

// BigInteger requires leading zero blocks to be truncated.
bitsBuffer = bitsBuffer.TrimEnd(0u);

Expand All @@ -477,26 +482,15 @@ private static ParsingStatus HexNumberToBigInteger(ref BigNumberBuffer number, o
sign = 0;
bits = null;
}
else if (bitsBuffer.Length == 1)
else if (bitsBuffer.Length == 1 && bitsBuffer[0] <= int.MaxValue)
{
sign = (int)bitsBuffer[0];
sign = (int)bitsBuffer[0] * (isNegative ? -1 : 1);
bits = null;

if ((!isNegative && sign < 0) || sign == int.MinValue)
{
bits = new[] { (uint)sign };
sign = isNegative ? -1 : 1;
}
}
else
{
sign = isNegative ? -1 : 1;
bits = bitsBuffer.ToArray();

if (isNegative)
{
NumericsHelpers.DangerousMakeTwosComplement(bits);
}
}

result = new BigInteger(sign, bits);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -132,6 +132,11 @@ public void Parse_Hex32Bits()
Assert.True(BigInteger.TryParse("080000001", NumberStyles.HexNumber, null, out result));
Assert.Equal(0x80000001u, result);

// Regression test for: https://github.com/dotnet/runtime/issues/74758
Assert.True(BigInteger.TryParse("FFFFFFFFE", NumberStyles.HexNumber, null, out result));
Assert.Equal(new BigInteger(-2), result);
Assert.Equal(-2, result);

Assert.Throws<FormatException>(() =>
{
BigInteger.Parse("zzz", NumberStyles.HexNumber);
Expand Down