CSharp - Essential Types BigInteger struct

Introduction

BigInteger struct from System.Numerics namespace in System.Numerics.dll represents an arbitrarily large integer without any loss of precision.

You can implicitly convert from any other integral type to a BigInteger. For instance:

BigInteger twentyFive = 25;      // implicit conversion from integer

To represent a bigger number, such as one googol (10100), you can use one of BigInteger's static methods, such as Pow (raise to the power):

BigInteger googol = BigInteger.Pow (10, 100);

Alternatively, you can Parse a string:

BigInteger googol = BigInteger.Parse ("1".PadRight (100, '0'));

Calling ToString() on this prints every digit:

Console.WriteLine (googol.ToString());

You can cast between BigInteger and the standard numeric types with the explicit cast operator:

double g2 = (double) googol;        // Explicit cast
BigInteger g3 = (BigInteger) g2;    // Explicit cast
Console.WriteLine (g3);

BigInteger overloads all the arithmetic operators including remainder (%), as well as the comparison and equality operators.

You can construct a BigInteger from a byte array.

The following code generates a 32-byte random number suitable for cryptography and then assigns it to a BigInteger:

Demo

using System;
using System.Numerics;
using System.Security.Cryptography;
class MainClass/*www.  ja v a2 s. co m*/
{
    public static void Main(string[] args)
    {
        RandomNumberGenerator rand = RandomNumberGenerator.Create();
        byte[] bytes = new byte[32];

        rand.GetBytes(bytes);
        var bigRandomNumber = new BigInteger(bytes);   // Convert to BigInteger

        Console.WriteLine(bigRandomNumber.ToString());

    }
}

Result

Calling ToByteArray converts a BigInteger back to a byte array.