Reputation: 626
How can I convert a big decimal integer to a byte array.
var number = "969837669069837851043825067021609343597253227631794160042862620526559";
Note that I can't use BigInteger
because I'm using Unity under .NET 3.5.
Upvotes: 0
Views: 1329
Reputation: 9824
You can write your own "BigInteger like type" but I would highly advise against it. It is one of those things were you can do a lot of stuff very wrong very quickly. And you will never even approach the efficiency of a builtin type like BigInteger.
I did write a TryParse replacement for someone stuck on 1.0 however, so I might be able to give you some hints:
As for the TryParse, here is what I wrote for that case way back:
//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;
}
Upvotes: 1
Reputation: 612
I, personally, would use BigInteger
. You can change Unity's scripting equivalent to .NET 4.6 under the player settings, which will give you access to a whole bunch of frameworks previously inaccessible. According to the documentation .NET 4.6 should contain BigInteger
, thus solving your issue.
To change the scripting equivalent, go to Build Settings
=> Player Settings
=> Other Settings
=> Configuration
. In that list of settings, you should be able to set the script runtime equivalent.
Once you've done that, all you have to do convert the number:
var number = "969837669069837851043825067021609343597253227631794160042862620526559";
byte[] numberBytes = BigInteger.Parse(number).ToByteArray();
Upvotes: 2