Skip to content

Commit

Permalink
Fix BigInteger parse hex strings on negative numbers (#84792)
Browse files Browse the repository at this point in the history
fixes #74758
  • Loading branch information
speshuric authored May 10, 2023
1 parent c77d916 commit 40438e0
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 13 deletions.
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

0 comments on commit 40438e0

Please sign in to comment.