1

I'm writing my magistracy work in cryptography, and today I was trying to get a BigInteger number from the string. But the only way I find to get BigInteger number from the string was

UTF8Encoding Encoding = new UTF8Encoding();
var bytes = Encoding.GetBytes(myString);
var myBigInteger = new BigInteger(bytes);

But this is not that way I need. I need something which will return me exactly BigInteger representation of the string. For example, if I have

var myString = "1234567890";

I want my BigInteger to be

BigInteger bi = 1234567890;
1
  • I've changed title to match your question (was: "how to get string from BigInteger", which looks complete opposite from the post)... Commented Jun 11, 2013 at 21:17

3 Answers 3

6

You could use that type's Parse method.

BigInteger.Parse(string value)

It's static. You pass a string and get the corresponding value.

For example:

BigInteger reallyBigNumber = BigInteger.Parse("12347534159895123");
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you! I forget about this at all =)
1

I think TryParse is the way you want to go:

BigInteger number1;
bool succeeded1 = BigInteger.TryParse("-12347534159895123", out number1);

This will not throw an exception if you pass an invalid value. It will just set the number to 0 if the input string will not convert. I believe it is faster than Parse as well.

http://msdn.microsoft.com/en-us/library/dd268301.aspx

6 Comments

It shoudn't be faster, since it uses Parse internally. It basically uses a try-catch block, returning true in the try block and false in the catch.
@Abe Why do you think that TryParse is faster than Parse method?
I read it somewhere a while back. Here is an excellent SO question where the accepted answer actually shows the difference in performance: stackoverflow.com/questions/150114/…
@Renan, do you have any sources that you could post backing up what you are saying? Not trying to be a smart ass, just curious to see where you are getting this.
@AbeMiessler while fidgeting with ILSpy a long time ago I noticed a pattern for all numeric types. I might be wrong, and unfortunately it seems that the latest .NET source codes made available by Microsoft don't include this type. So I can't back up what I said :( please disregard it.
|
0
BigInteger bi = BigInteger.Parse("1234567890");

Comments

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.