任意大的整数,在C# [英] Arbitrarily large integers in C#

查看:218
本文介绍了任意大的整数,在C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我如何在C#中实现这条巨蟒code?

How can I implement this python code in c#?

Python的code:

Python code:

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

结果:

305802052421002911840647389720929531201

但在C#我有问题,大的数字。

But in c# I have problems with big digits.

您能帮我吗?

我有在Python和C#不同的结果。在哪里可以是错误的?

I've got different results in python and c#. Where can be mistake?

推荐答案

基本类型(如的Int32 的Int64 )有一个有限的长度,它是不够的,这么大的数量。例如:

Primitive types (such as Int32, Int64) have a finite length that it's not enough for such big number. For example:


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

在这种情况下,要重新present这个数字,你就需要128位。在.NET Framework 4.0中存在的任意大小的整数一个新的数据类型<一href="http://msdn.microsoft.com/en-us/library/system.numerics.biginteger.aspx">System.Numerics.BigInteger.您不需要指定任何大小,因为这将是的推断的由编号本身(这意味着,你甚至可以得到一个 OutOfMemoryException异常当你执行,例如,两个非常大的数字乘法)。

In this case to represent that number you would need 128 bits. With .NET Framework 4.0 there is a new data type for arbitrarily sized integer numbers System.Numerics.BigInteger. You do not need to specify any size because it'll be inferred by the number itself (it means that you may even get an OutOfMemoryException when you perform, for example, a multiplication of two very big numbers).

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

To come back to your question, first parse your hexadecimal number:

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

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

Then simply print it to console:

Console.WriteLine(bigNumber.ToString());

您可能会感兴趣,计算有多少位需要重新present任意数,使用此功能(如果我记得很清楚最初的实现来自C数字食谱):

You may be interested to calculate how many bits you need to represent an arbitrary number, use this function (if I remember well original implementation comes from C Numerical Recipes):

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

   return neededBits;
}

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

Then to calculate the required size of a number wrote as string:

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

这篇关于任意大的整数,在C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆