简体   繁体   中英

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. :)

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM