考虑以下代码:
ulong max = ulong.MaxValue;
byte[] maxBytes = BitConverter.GetBytes(max);
BigInteger a = new BigInteger(max);
BigInteger b = new BigInteger(maxBytes);
Console.WriteLine(a); // 18446744073709551615
Console.WriteLine(b); // -1
为什么从 ulong.MaxValue
的 byte[]
表示形式创建 BigInteger
实例不会产生预期的 结果 (18446744073709551615)?
最佳答案
BigInteger 有符号,而 ulong 则没有。
因为 ulong 没有符号,所以它的最大值以字节为单位,但对于有符号值,最高有效位表示极性。
当您使用 ulong 构造时,BigInteger 可以看到该值并使用它,但是当您将其作为字节数组传递时,全 1 字节数组的 SIGNED 解释为负一。
关于C# - 来自字节数组的 BigInteger 与来自 UInt64 的 BigInteger 产生不同的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73175529/