Convert BigInteger to byte array in CSharp
Description
The following code shows how to convert BigInteger to byte array.
Example
using System;// w w w. ja v a 2 s . co m
using System.Numerics;
public class Example
{
public static void Main()
{
BigInteger positiveValue = BigInteger.Parse("9999999999999999999999999");
BigInteger negativeValue = BigInteger.Add(-Int64.MaxValue, -60000);
BigInteger positiveValue2, negativeValue2;
// Create two byte arrays.
byte[] positiveBytes = positiveValue.ToByteArray();
byte[] negativeBytes = negativeValue.ToByteArray();
// Instantiate new BigInteger from negativeBytes array.
Console.Write("Converted {0:N0} to the byte array ", negativeValue);
foreach (byte byteValue in negativeBytes)
Console.Write("{0:X2} ", byteValue);
negativeValue2 = new BigInteger(negativeBytes);
Console.WriteLine("Converted the byte array to {0:N0}", negativeValue2);
// Instantiate new BigInteger from positiveBytes array.
Console.Write("Converted {0:N0} to the byte array ", positiveValue);
foreach (byte byteValue in positiveBytes)
Console.Write("{0:X2} ", byteValue);
positiveValue2 = new BigInteger(positiveBytes);
Console.WriteLine("Converted the byte array to {0:N0}", positiveValue2);
}
}
The code above generates the following result.