[英]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.