0

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

3
  • So one idea: a single decimal digit does not occupy one full byte. Commented Feb 12, 2014 at 11:14
  • I don't understand your question clearly but BigInteger structure has an Byte array constructor. Did you tried it? Note: It is not a CLS compliant. Commented Feb 12, 2014 at 11:15
  • BigInteger in c# is small - I need work with cca 2048 bit numbers. Commented Feb 12, 2014 at 11:31

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

BigInteger in c# is small for me :( - I need work with cca 2048 bit numbers.
@user3299032 But C# integer works with 2048 bit numbers (and much more), so what is your actual problem?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.