C#中任意大的整数

9

我该如何在C#中实现这段Python代码?

Python代码:

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

结果:

305802052421002911840647389720929531201

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

你能帮助我吗?

我在Python和C#中得到了不同的结果,可能出了什么错误?

3个回答

25

基本数据类型(例如Int32Int64)有限长度,不足以表示如此大的数字。例如:

数据类型                                          最大正数值
Int32                                                       2,147,483,647
UInt32                                                      4,294,967,295
Int64                                       9,223,372,036,854,775,808
UInt64                                     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 Numerical Recipes):
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));
}

谢谢!它能工作!但是返回错误的结果,这可能只是时间问题。也许...=) - pic0

3

如果您只想使用更大的数字,可以使用BigInteger,它具有许多位数。


1

要找到存储BigInteger N所需的位数,您可以使用以下方法:

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接