user3299032
user3299032

Reputation: 53

String of decimal numbers to byte array [c#]

I have problem in c# with convert decimal number from string to byte array. I want creat BigInteger with using byte array.

I try:

string Astr = "123456789123456789123456789123456789123456789123456789123456789123456789123456789";
byte[] AByte = Astr.Select(c => (byte)(c - '0')).ToArray(); //This is problem because array padding wrong.

Tnaks for your ideas. :)

Upvotes: 0

Views: 338

Answers (1)

Matthew Watson
Matthew Watson

Reputation: 109732

Why do you need to create the BigInteger from a byte array when you have the string available?

Why not just do this?

string aStr = "123456789123456789123456789123456789123456789123456789123456789123456789123456789";
BigInteger x = BigInteger.Parse(aStr);

Also note that there is no easy correspondence between a BigInteger in string form and its byte array.

For example, following on from the code above, if you add this:

var ba = x.ToByteArray();
Console.WriteLine(string.Join(" ", ba.Select(v => v.ToString("x"))));

The output is:

15 5f 4 84 b6 70 28 c7 73 7b a3 d5 f9 b a1 8 67 12 b0 a5 af 52 ba cb e4 66 6c 75 78 66 92 31 2a 4

Which is the byte[] version of the original string after being encoded as a BigInteger.

Upvotes: 1

Related Questions