This is a mirror of official site: http://jasper-net.blogspot.com/

Really, Really, Big Numbers with BigInteger in .NET 4.0

| Monday, August 23, 2010
The .NET Framework has literally thousands (maybe tens of thousands) of hidden gems. In the dark ages programmers learned a language’s grammar and a few dozen keywords and used—don’t say it—books to learn about a language’s function library. Literally, you could pick up a new language relatively quickly—except for C++—but it was still hard to use because one had to read analog books; Kindle didn’t even exist. Now if you want to learn a new language or framework you can still pick up the keywords and grammar pretty quickly, but the frameworks are massive. If one had to search a book to figure out how to use the .NET Framework it would be an impossible task. Thankfully, with Google, Wikipedia, blogs, and searchable articles if a developer can state a problem in plain English then there is probably some sample code that demonstrates a solution. I would venture to say that with content being added daily a developer can find a solution to almost any programming problem. This blog is my homage to the Web eventually covering everything.

.NET 4.0 added the BigInteger. BigInteger theoretically has no upper or lower limit, which is why it has no MinValue or MaxValue properties like other numeric types. You can assign a BigInteger a number as big as your computer’s memory will permit. For example, I computed Fibonacci numbers—by adding the previous two numbers 1,1,2,3,5,8,13,21,34,etc—and assigned them to BigInteger; the numbers were very huge very quickly with no end in sight.

You can use BigInteger much as you would an other integer type in .NET, but you can’t use the Math class with BigInteger. The Math class so far hasn’t been retrofitted for BigInteger. However, BigInteger has its own methods and overloaded operators that provide many of the same capabilities as other integer types have, except square root, which we will come back to. BigIntegers can be initialized with string, byte arrays, and smaller integer types. If you want to initialize a BigInteger with a byte array then it is worth noting that BigInteger stores data in little-endian order—lower order bytes precede higher-order bytes in the array. Positive values are interpreted by the most significant bit of the last byte; that is, the last bit of the last byte in the array is the sign bit. If you want to create a positive BigInteger with a byte array then place a 0 as the last element of the byte array. For example,

new BigInteger(new byte[]{255});

creates a BigInteger with the value –1 and

new BigInteger(new byte[]{255, 0});

creates a BigInteger with the value of 255.

Read more: Paul Kimmel's Blog

Posted via email from .NET Info

0 comments: