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;
Alexei Levenkov
  • 98,904
  • 14
  • 127
  • 179
Art713
  • 485
  • 4
  • 14
  • I've changed title to match your question (was: "how to get string from `BigInteger`", which looks complete opposite from the post)... – Alexei Levenkov Jun 11 '13 at 21:17

3 Answers3

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");
Geeky Guy
  • 9,229
  • 4
  • 42
  • 62
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

Abe Miessler
  • 82,532
  • 99
  • 305
  • 486
  • 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`. – Geeky Guy Jun 11 '13 at 21:34
  • @Abe Why do you think that TryParse is faster than Parse method? – Art713 Jun 11 '13 at 21:35
  • I read it somewhere a while back. Here is an excellent SO question where the accepted answer actually shows the difference in performance: http://stackoverflow.com/questions/150114/parsing-performance-if-tryparse-try-catch – Abe Miessler Jun 11 '13 at 21:37
  • @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. – Abe Miessler Jun 11 '13 at 21:39
  • @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. – Geeky Guy Jun 11 '13 at 21:46
  • Interesting question either way. I'd be curious to see how it's actually implemented. – Abe Miessler Jun 11 '13 at 21:47
0
BigInteger bi = BigInteger.Parse("1234567890");
Tim B
  • 2,340
  • 15
  • 21