C#中任意大整数

pic*_*ic0 7 .net c# python biginteger

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

Python代码:

print(str(int(str("e60f553e42aa44aebf1d6723b0be7541"), 16)))
Run Code Online (Sandbox Code Playgroud)

结果:

305802052421002911840647389720929531201
Run Code Online (Sandbox Code Playgroud)

但是在c#中我遇到了大数字问题.

你能帮助我吗?

我在python和c#中得到了不同的结果.哪里可以搞错?

Adr*_*tti 22

原始类型(例如Int32,Int64)具有有限的长度,这对于如此大的数字是不够的.例如:

Data type                                     Maximum positive value
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
Your number      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);
Run Code Online (Sandbox Code Playgroud)

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

Console.WriteLine(bigNumber.ToString());
Run Code Online (Sandbox Code Playgroud)

您可能有兴趣计算需要多少位来表示任意数字,使用此函数(如果我记得原始实现来自C Numerical Recipes):

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

   return neededBits;
}
Run Code Online (Sandbox Code Playgroud)

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

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


ann*_*sly 3

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