簡體   English   中英

C#將大十進制數轉換為字節數組

[英]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的人,所以我可能會給你一些提示:

  • 使用UnsignedIntegers列表。 使用最大的avalable整數作為基本類型,這樣索引將保持很小。 還有一個列表,因為您也不想處理整數的增長/縮小
  • 對任意兩個元素進行數學運算時,請更改為檢查的上下文 .NET Framework可以完全檢測上溢和下溢錯誤,但是默認情況下該檢測處於關閉狀態。 如果出現上溢或下溢錯誤,則意味着您應該相應地增加/減少下一位數字
  • 大部分的方法都需要至少一個臨時變量。 對於加法和減法,您需要存儲上溢/下溢情況。 對於乘法,您需要將ListA的每個數組元素與ListB的每個數組元素相乘。 您只需將每個值ListA與ListB的一個元素相乘。 將其放入一些臨時變量中。 然后將其添加到運行總和。
  • 這篇關於平等/身份檢查的文章可能會幫助您正確地完成這一部分: http : //www.codeproject.com/Articles/18714/Comparing-Values-for-Equality-in-NET-Identity-,並且您想要值類型語義。
  • 理想情況下,您要使此類型不可變。 大多數集成類型和字符串都是(包括BigInteger),因此在多任務/線程方案中使用它們更容易。
  • 您可能需要進行解析和toString()。 如果是這樣,適當的區域性格式化可能很快就會成為問題。 大多數數值類型都具有接受CultureNumberFormat作為參數的Parse()和toString()函數。 默認重載只是恢復線程區域性/其他一些默認值,然后將其交給兄弟。

至於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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM