C#将大十进制数转换为字节数组

时间:2018-03-10 14:50:55

标签: c# integer .net-3.5

如何将大十进制整数转换为字节数组。

var number = "969837669069837851043825067021609343597253227631794160042862620526559";

请注意,我无法使用BigInteger,因为我在.NET 3.5下使用Unity。

2 个答案:

答案 0 :(得分:2)

我个人会使用BigInteger。您可以在播放器设置下更改与.NET 4.6等效的Unity脚本,这样您就可以访问以前无法访问的一大堆框架。根据{{​​3}} .NET 4.6应该包含BigInteger,从而解决您的问题。

要更改脚本等效内容,请转到Build Settings => Player Settings => Other Settings => Configuration。在该设置列表中,您应该能够设置等效的脚本运行时。

完成后,您需要做的就是转换数字:

var number = "969837669069837851043825067021609343597253227631794160042862620526559";
byte[] numberBytes = BigInteger.Parse(number).ToByteArray();

答案 1 :(得分:1)

你可以编写自己的“BigInteger like type”,但我会高度建议反对它。这是其中一件事,你可以很快地做很多非常错误的事情。你永远不会像BigInteger那样接近内置类型的效率。

我确实为那些卡在1.0上的人写了一个TryParse替代品,所以我可能会给你一些提示:

  • 使用UnsignedIntegers列表。使用最大的整数作为基本类型,这样索引将保持小巧。还有一个列表,因为你不想处理整数的增长/收缩
  • 在对任何两个元素进行数学运算时更改为checked context。 .NET Framework可以完全检测溢出下溢错误,但默认情况下关闭该检测。如果出现上溢或下溢错误,则表示您应相应地增加/减少下一个数字
  • 大多数arythmethic需要至少一个临时变量。对于加法和减法,您需要存储溢出/下溢情况。对于乘法,您需要将ListA的每个数组元素与ListB的每个数组元素相乘。您只需将每个值ListA与ListB的一个Element相乘。把它放入一些临时变量。然后将其添加到运行总和中。
  • 这篇关于相等/身份检查的文章可能会帮助你正确地完成这一部分:http://www.codeproject.com/Articles/18714/Comparing-Values-for-Equality-in-NET-Identity-and你想要值类型Semantics。
  • 理想情况下,您希望将此类型设为不可变。大多数集成类型和字符串都是(包括BigInteger),因此在多任务/线程场景中更容易使用它们。
  • 您可能需要进行解析和toString()。如果是这样,文化适应性格式化可能会很快成为一个问题。大多数数字类型都有Parse()和toString()函数,它接受CultureNumberFormat作为参数。默认重载只是简单地检索线程文化/其他一些默认值,并将其交给他们的兄弟。

至于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;

}