C#中任意大整数
如何在c#中实现这个python代码?
Python代码:
print(str(int(str("e60f553e42aa44aebf1d6723b0be7541"), 16)))
结果:
305802052421002911840647389720929531201
但是在c#中我遇到了大数字问题。
你能帮助我吗?
我在python和c#中得到了不同的结果。 哪里可能是错误的?
原始类型(例如Int32
, Int64
)具有有限的长度,这对于如此大的数字是不够的。 例如:
数据类型 最大正值 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
,例如,两个非常大的数字相乘)。
要回到您的问题,首先解析您的hex数:
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)); }
如果你只想使用更大的数字,那么BigInteger
就有很多数字。