From a4878bfff6ab9751ef8f5ef28a67b5e3404c43bf Mon Sep 17 00:00:00 2001 From: Rob Hague Date: Sun, 10 Nov 2024 13:53:28 +0100 Subject: [PATCH] Fix BigInteger bitwise operators on certain negative numbers --- .../src/System/Numerics/BigInteger.cs | 4 ++-- .../tests/BigInteger/op_and.cs | 17 +++++++++++++++++ 2 files changed, 19 insertions(+), 2 deletions(-) diff --git a/src/libraries/System.Runtime.Numerics/src/System/Numerics/BigInteger.cs b/src/libraries/System.Runtime.Numerics/src/System/Numerics/BigInteger.cs index e4d8845dd05e81..b3355ff68678ca 100644 --- a/src/libraries/System.Runtime.Numerics/src/System/Numerics/BigInteger.cs +++ b/src/libraries/System.Runtime.Numerics/src/System/Numerics/BigInteger.cs @@ -544,9 +544,9 @@ private BigInteger(Span value) isNegative = true; length = value.LastIndexOfAnyExcept(uint.MaxValue) + 1; - if ((length == 0) || ((int)value[length - 1] > 0)) + if ((length == 0) || ((int)value[length - 1] >= 0)) { - // We ne need to preserve the sign bit + // We need to preserve the sign bit length++; } Debug.Assert((int)value[length - 1] < 0); diff --git a/src/libraries/System.Runtime.Numerics/tests/BigInteger/op_and.cs b/src/libraries/System.Runtime.Numerics/tests/BigInteger/op_and.cs index ed25708e2d0c6d..ca97422b451c10 100644 --- a/src/libraries/System.Runtime.Numerics/tests/BigInteger/op_and.cs +++ b/src/libraries/System.Runtime.Numerics/tests/BigInteger/op_and.cs @@ -1,6 +1,7 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +using System.Runtime.InteropServices; using Xunit; namespace System.Numerics.Tests @@ -117,6 +118,22 @@ public static void RunAndTests() } } + [Fact] + public void Issue109669() + { + // Operations on numbers whose result is of the form 0xFFFFFFFF 00000000 ... 00000000 + // in two's complement. + + Assert.Equal(-4294967296, new BigInteger(-4294967296) & new BigInteger(-1919810)); + Assert.Equal(-4294967296, new BigInteger(-4042322161) & new BigInteger(-252645136)); + Assert.Equal(-4294967296, new BigInteger(-8589934592) | new BigInteger(-21474836480)); + + BigInteger a = new BigInteger(MemoryMarshal.AsBytes([uint.MaxValue, 0u, 0u]), isBigEndian: true); + Assert.Equal(a, a & a); + Assert.Equal(a, a | a); + Assert.Equal(a, a ^ 0); + } + private static void VerifyAndString(string opstring) { StackCalc sc = new StackCalc(opstring);