C# 中的任意大整数

本文关键字:整数 任意大 | 更新日期: 2023-09-27 18:32:00

如何在 c# 中实现此 python 代码?

蟒蛇代码:

print(str(int(str("e60f553e42aa44aebf1d6723b0be7541"), 16)))

结果:

305802052421002911840647389720929531201

但是在 c# 中,我遇到了大数字的问题。

你可以帮我吗?

我在python和c#中得到了不同的结果。哪里会出错?

C# 中的任意大整数

元类型(如Int32Int64)的长度有限,对于这么大的数字来说是不够的。例如:

数据类型最大正值Int32 2,147,483,647UInt32 4,294,967,295Int64 9,223,372,036,854,775,808UInt64 18,446,744,073,709,551,615您的号码 305,802,052,421,002,911,840,647,389,720,929,531,201

在这种情况下,要表示该数字,您需要 128 位。在 .NET Framework 4.0 中,为任意大小的整数 System.Numerics.BigInteger 提供了一种新的数据类型。您不需要指定任何大小,因为它将由数字本身推断(这意味着当您执行时,例如,两个非常大的数字的乘法,您甚至可能会得到一个OutOfMemoryException)。

回到你的问题,首先解析你的十六进制数:

string bigNumberAsText = "e60f553e42aa44aebf1d6723b0be7541";
BigInteger bigNumber = BigInteger.Parse(bigNumberAsText,
    NumberStyles.AllowHexSpecifier);

然后只需将其打印到控制台:

Console.WriteLine(bigNumber.ToString());

您可能有兴趣计算表示任意数字所需的位数,请使用此函数(如果我记得不错,原始实现来自 C 数值配方):

public static uint GetNeededBitsToRepresentInteger(BigInteger value)
{
   uint neededBits = 0;
   while (value != 0)
   {
      value >>= 1;
      ++neededBits;
   }
   return neededBits;
}

然后计算写为字符串的数字所需的大小:

public static uint GetNeededBitsToRepresentInteger(string value,
   NumberStyles numberStyle = NumberStyles.None)
{
   return GetNeededBitsToRepresentInteger(
      BigInteger.Parse(value, numberStyle));
}

如果你只是想使用更大的数字,BigInteger有很多数字。

要查找存储BigInteger N所需的位数,您可以使用:

BigInteger N = ...;
int nBits = Mathf.CeilToInt((float)BigInteger.Log(N, 2.0));