[英]C# Convert big decimal numbers to byte array
如何将大十进制整数转换为字节数组。
var number = "969837669069837851043825067021609343597253227631794160042862620526559";
请注意,我无法使用BigInteger
因为我在.NET 3.5下使用Unity。
我个人将使用BigInteger
。 您可以在播放器设置下更改与.NET 4.6等效的Unity脚本,这将使您可以访问以前无法访问的大量框架。 根据文档, .NET 4.6应该包含BigInteger
,从而解决您的问题。
要更改等效脚本,请转到Build Settings
=> Player Settings
=> Other Settings
=> Configuration
。 在该设置列表中,您应该能够设置脚本运行时等效项。
完成此操作后,您要做的就是转换数字:
var number = "969837669069837851043825067021609343597253227631794160042862620526559";
byte[] numberBytes = BigInteger.Parse(number).ToByteArray();
您可以编写自己的“ BigInteger like type”,但我强烈建议您这样做。 这是其中的一件事,您可以很快地做很多非常错误的事情。 而且,您甚至永远也不会达到像BigInteger这样的内置类型的效率。
我确实写了一个TryParse替代品来代替坚持1.0的人,所以我可能会给你一些提示:
至于TryParse,这是我为这种情况写的:
//Parse throws ArgumentNull, Format and Overflow Exceptions.
//And they only have Exception as base class in common, but identical handling code (output = 0 and return false).
bool TryParse(string input, out int output){
try{
output = int.Parse(input);
}
catch (Exception ex){
if(ex is ArgumentNullException ||
ex is FormatException ||
ex is OverflowException){
//these are the exceptions I am looking for. I will do my thing.
output = 0;
return false;
}
else{
//Not the exceptions I expect. Best to just let them go on their way.
throw;
}
}
//I am pretty sure the Exception replaces the return value in exception case.
//So this one will only be returned without any Exceptions, expected or unexpected
return true;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.