C# - 来自字节数组的 BigInteger 与来自 UInt64 的 BigInteger 产生不同的结果

标签 c# arrays biginteger ulong

考虑以下代码:

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.MaxValuebyte[] 表示形式创建 BigInteger 实例不会产生预期的 结果 (18446744073709551615)?

最佳答案

BigInteger 有符号,而 ulong 则没有。

因为 ulong 没有符号,所以它的最大值以字节为单位,但对于有符号值,最高有效位表示极性。

当您使用 ulong 构造时,BigInteger 可以看到该值并使用它,但是当您将其作为字节数组传递时,全 1 字节数组的 SIGNED 解释为负一。

关于C# - 来自字节数组的 BigInteger 与来自 UInt64 的 BigInteger 产生不同的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73175529/

相关文章:

c# - 线程不一致

c# - C#动态创建Type数组

Java 数组存储值

Java 在 BigInteger 中存储字符串

java - 奇怪的 BigInteger.mod 模数方法

java - 为什么 java.Math.BigInteger 在一定限制后会出错?

c# - 从代码隐藏在 MVC 中生成 Url

c# - 为什么用户控件不从 View 模型绑定(bind)?

c# - 更改标签的位置

php - 获取 PHP 数组中的最小值并获取对应的键