Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
442 views
in Technique[技术] by (71.8m points)

c# - BigInteger Parse Octal String?

In Java, I could do

//Parsing Octal String
BigInteger b = new BigInteger("16304103460644701340432043410021040424210140423204",8);

Then format it as I pleased

b.toString(2); //2 for binary
b.toString(10); //10 for decimal
b.toString(16); //16 for hexadecimal

C#'s BigInteger offers the formatting capabilities shown above but I can't seem to find a way to parse BIIIG (greater than 64 bit, unsigned) Octal values.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

This may not be the most efficient solution, but if performance is not a priority, you can construct the BigInteger manually:

string s = "16304103460644701340432043410021040424210140423204";
BigInteger bi = s.Aggregate(new BigInteger(), (b, c) => b * 8 + c - '0');

The above solution also works for any base not greater than 10; just replace the 8 in the above code with your required base.

Edit: For hexadecimal numbers, you should use the Parse method. Prepend with 0 if your number should be interpreted as positive even if its first character is 8F.

string s = "0F20051C5E45F4FD68F8E58905A133BCA";
BigInteger bi = BigInteger.Parse(s, NumberStyles.HexNumber);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...