【问题标题】:Arbitrarily large integers in C#C#中的任意大整数
【发布时间】:2012-04-24 07:32:01
【问题描述】:

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

Python 代码:

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

结果:

305802052421002911840647389720929531201

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

你能帮帮我吗?

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

【问题讨论】:

    标签: c# .net python biginteger


    【解决方案1】:

    原始类型(例如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));
    }
    

    【讨论】:

    • 谢谢!有用!但是返回错误的结果,这是时间问题。也许...=)
    【解决方案2】:

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

    【讨论】:

      【解决方案3】:

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

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

      【讨论】:

        猜你喜欢
        • 2015-04-25
        • 2017-04-06
        • 1970-01-01
        • 2023-03-28
        • 1970-01-01
        • 2010-09-07
        • 2012-06-18
        • 2015-11-20
        相关资源
        最近更新 更多