Udostępnij za pośrednictwem


BigInteger Structure

Microsoft Silverlight will reach end of support after October 2021. Learn more.

Represents an arbitrarily large signed integer.

Namespace:  System.Numerics
Assembly:  System.Numerics (in System.Numerics.dll)

Syntax

'Declaration
Public Structure BigInteger _
    Implements IFormattable, IComparable, IComparable(Of BigInteger),  _
    IEquatable(Of BigInteger)
public struct BigInteger : IFormattable, 
    IComparable, IComparable<BigInteger>, IEquatable<BigInteger>

The BigInteger type exposes the following members.

Constructors

  Name Description
Public method BigInteger(array<Byte[]) Initializes a new instance of the BigInteger structure using the values in a byte array.
Public method BigInteger(Decimal) Initializes a new instance of the BigInteger structure using a Decimal value.
Public method BigInteger(Double) Initializes a new instance of the BigInteger structure using a double-precision floating-point value.
Public method BigInteger(Int32) Initializes a new instance of the BigInteger structure using a 32-bit signed integer value.
Public method BigInteger(Int64) Initializes a new instance of the BigInteger structure using a 64-bit signed integer value.
Public method BigInteger(Single) Initializes a new instance of the BigInteger structure using a single-precision floating-point value.
Public method BigInteger(UInt32) Initializes a new instance of the BigInteger structure using an unsigned 32-bit integer value.
Public method BigInteger(UInt64) Initializes a new instance of the BigInteger structure with an unsigned 64-bit integer value.

Top

Properties

  Name Description
Public property IsEven Indicates whether the value of the current BigInteger object is an even number.
Public property IsOne Indicates whether the value of the current BigInteger object is BigInteger.One.
Public property IsPowerOfTwo Indicates whether the value of the current BigInteger object is a power of two.
Public property IsZero Indicates whether the value of the current BigInteger object is BigInteger.Zero.
Public propertyStatic member MinusOne Gets a value that represents the number negative one (-1).
Public propertyStatic member One Gets a value that represents the number one (1).
Public property Sign Gets a number that indicates the sign (negative, positive, or zero) of the current BigInteger object.
Public propertyStatic member Zero Gets a value that represents the number 0 (zero).

Top

Methods

  Name Description
Public methodStatic member Abs Gets the absolute value of a BigInteger object.
Public methodStatic member Add Adds two BigInteger values and returns the result.
Public methodStatic member Compare Compares two BigInteger values and returns an integer that indicates whether the first value is less than, equal to, or greater than the second value.
Public method CompareTo(BigInteger) Compares this instance to a second BigInteger and returns an integer that indicates whether the value of this instance is less than, equal to, or greater than the value of the specified object.
Public method CompareTo(Int64) Compares this instance to a signed 64-bit integer and returns an integer that indicates whether the value of this instance is less than, equal to, or greater than the value of the signed 64-bit integer.
Public method CompareTo(Object) Compares this instance to a specified object and returns an integer that indicates whether the value of this instance is less than, equal to, or greater than the value of the specified object.
Public method CompareTo(UInt64) Compares this instance to an unsigned 64-bit integer and returns an integer that indicates whether the value of this instance is less than, equal to, or greater than the value of the unsigned 64-bit integer.
Public methodStatic member Divide Divides one BigInteger value by another and returns the result.
Public methodStatic member DivRem Divides one BigInteger value by another, returns the result, and returns the remainder in an output parameter.
Public method Equals(BigInteger) Returns a value that indicates whether the current instance and a specified BigInteger object have the same value.
Public method Equals(Int64) Returns a value that indicates whether the current instance and a signed 64-bit integer have the same value.
Public method Equals(Object) Returns a value that indicates whether the current instance and a specified object have the same value. (Overrides ValueType.Equals(Object).)
Public method Equals(UInt64) Returns a value that indicates whether the current instance and an unsigned 64-bit integer have the same value.
Protected method Finalize Allows an object to try to free resources and perform other cleanup operations before the Object is reclaimed by garbage collection. (Inherited from Object.)
Public method GetHashCode Returns the hash code for the current BigInteger object. (Overrides ValueType.GetHashCode().)
Public method GetType Gets the Type of the current instance. (Inherited from Object.)
Public methodStatic member GreatestCommonDivisor Finds the greatest common divisor of two BigInteger values.
Public methodStatic member Log(BigInteger) Returns the natural (base e) logarithm of a specified number.
Public methodStatic member Log(BigInteger, Double) Returns the logarithm of a specified number in a specified base.
Public methodStatic member Log10 Returns the base 10 logarithm of a specified number.
Public methodStatic member Max Returns the larger of two BigInteger values.
Protected method MemberwiseClone Creates a shallow copy of the current Object. (Inherited from Object.)
Public methodStatic member Min Returns the smaller of two BigInteger values.
Public methodStatic member ModPow Performs modulus division on a number raised to the power of another number.
Public methodStatic member Multiply Returns the product of two BigInteger values.
Public methodStatic member Negate Negates a specified BigInteger value.
Public methodStatic member Pow Raises a BigInteger value to the power of a specified value.
Public methodStatic member Remainder Performs integer division on two BigInteger values and returns the remainder.
Public methodStatic member Subtract Subtracts one BigInteger value from another and returns the result.
Public method ToByteArray Converts a BigInteger value to a byte array.
Public method ToString() Converts the numeric value of the current BigInteger object to its equivalent string representation. (Overrides ValueType.ToString().)
Public method ToString(IFormatProvider) Converts the numeric value of the current BigInteger object to its equivalent string representation by using the specified culture-specific formatting information.
Public method ToString(String) Converts the numeric value of the current BigInteger object to its equivalent string representation by using the specified format.
Public method ToString(String, IFormatProvider) Converts the numeric value of the current BigInteger object to its equivalent string representation by using the specified format and culture-specific format information.

Top

Operators

  Name Description
Public operatorStatic member Addition Adds the values of two specified BigInteger objects.
Public operatorStatic member BitwiseAnd Performs a bitwise And operation on two BigInteger values.
Public operatorStatic member BitwiseOr Performs a bitwise Or operation on two BigInteger values.
Public operatorStatic member Decrement Decrements a BigInteger value by 1.
Public operatorStatic member Division Divides a specified BigInteger value by another specified BigInteger value by using integer division.
Public operatorStatic member Equality(BigInteger, Int64) Returns a value that indicates whether a BigInteger value and a signed long integer value are equal.
Public operatorStatic member Equality(BigInteger, BigInteger) Returns a value that indicates whether the values of two BigInteger objects are equal.
Public operatorStatic member Equality(BigInteger, UInt64) Returns a value that indicates whether a BigInteger value and an unsigned long integer value are equal.
Public operatorStatic member Equality(Int64, BigInteger) Returns a value that indicates whether a signed long integer value and a BigInteger value are equal.
Public operatorStatic member Equality(UInt64, BigInteger) Returns a value that indicates whether an unsigned long integer value and a BigInteger value are equal.
Public operatorStatic member ExclusiveOr Performs a bitwise exclusive Or (XOr) operation on two BigInteger values.
Public operatorStatic member Explicit(BigInteger to UInt16) Defines an explicit conversion of a BigInteger object to an unsigned 16-bit integer value.
Public operatorStatic member Explicit(BigInteger to Int32) Defines an explicit conversion of a BigInteger object to a 32-bit signed integer value.
Public operatorStatic member Explicit(BigInteger to Int16) Defines an explicit conversion of a BigInteger object to a 16-bit signed integer value.
Public operatorStatic member Explicit(BigInteger to Byte) Defines an explicit conversion of a BigInteger object to an unsigned byte value.
Public operatorStatic member Explicit(BigInteger to SByte) Defines an explicit conversion of a BigInteger object to a signed 8-bit value.
Public operatorStatic member Explicit(BigInteger to UInt32) Defines an explicit conversion of a BigInteger object to an unsigned 32-bit integer value.
Public operatorStatic member Explicit(BigInteger to Single) Defines an explicit conversion of a BigInteger object to a single-precision floating-point value.
Public operatorStatic member Explicit(BigInteger to UInt64) Defines an explicit conversion of a BigInteger object to an unsigned 64-bit integer value.
Public operatorStatic member Explicit(BigInteger to Int64) Defines an explicit conversion of a BigInteger object to a 64-bit signed integer value.
Public operatorStatic member Explicit(BigInteger to Double) Defines an explicit conversion of a BigInteger object to a Double value.
Public operatorStatic member Explicit(BigInteger to Decimal) Defines an explicit conversion of a BigInteger object to a Decimal value.
Public operatorStatic member Explicit(Decimal to BigInteger) Defines an explicit conversion of a Decimal object to a BigInteger value.
Public operatorStatic member Explicit(Double to BigInteger) Defines an explicit conversion of a Decimal object to a BigInteger value.
Public operatorStatic member Explicit(Single to BigInteger) Defines an explicit conversion of a Single object to a BigInteger value.
Public operatorStatic member GreaterThan(BigInteger, Int64) Returns a value that indicates whether a BigInteger is greater than a 64-bit signed integer value.
Public operatorStatic member GreaterThan(BigInteger, BigInteger) Returns a value that indicates whether a BigInteger value is greater than another BigInteger value.
Public operatorStatic member GreaterThan(BigInteger, UInt64) Returns a value that indicates whether a BigInteger value is greater than a 64-bit unsigned integer.
Public operatorStatic member GreaterThan(Int64, BigInteger) Returns a value that indicates whether a 64-bit signed integer is greater than a BigInteger value.
Public operatorStatic member GreaterThan(UInt64, BigInteger) Returns a value that indicates whether a BigInteger value is greater than a 64-bit unsigned integer.
Public operatorStatic member GreaterThanOrEqual(BigInteger, Int64) Returns a value that indicates whether a BigInteger value is greater than or equal to a 64-bit signed integer value.
Public operatorStatic member GreaterThanOrEqual(BigInteger, BigInteger) Returns a value that indicates whether a BigInteger value is greater than or equal to another BigInteger value.
Public operatorStatic member GreaterThanOrEqual(BigInteger, UInt64) Returns a value that indicates whether a BigInteger value is greater than or equal to a 64-bit unsigned integer value.
Public operatorStatic member GreaterThanOrEqual(Int64, BigInteger) Returns a value that indicates whether a 64-bit signed integer is greater than or equal to a BigInteger value.
Public operatorStatic member GreaterThanOrEqual(UInt64, BigInteger) Returns a value that indicates whether a 64-bit unsigned integer is greater than or equal to a BigInteger value.
Public operatorStatic member Implicit(Byte to BigInteger) Defines an implicit conversion of an unsigned byte to a BigInteger value.
Public operatorStatic member Implicit(Int16 to BigInteger) Defines an implicit conversion of a signed 16-bit integer to a BigInteger value.
Public operatorStatic member Implicit(Int32 to BigInteger) Defines an implicit conversion of a signed 32-bit integer to a BigInteger value.
Public operatorStatic member Implicit(Int64 to BigInteger) Defines an implicit conversion of a signed 64-bit integer to a BigInteger value.
Public operatorStatic member Implicit(SByte to BigInteger) Defines an implicit conversion of an 8-bit signed integer to a BigInteger value.
Public operatorStatic member Implicit(UInt16 to BigInteger) Defines an implicit conversion of a 16-bit unsigned integer to a BigInteger value.
Public operatorStatic member Implicit(UInt32 to BigInteger) Defines an implicit conversion of a 32-bit unsigned integer to a BigInteger value.
Public operatorStatic member Implicit(UInt64 to BigInteger) Defines an implicit conversion of a 64-bit unsigned integer to a BigInteger value.
Public operatorStatic member Increment Increments a BigInteger value by 1.
Public operatorStatic member Inequality(BigInteger, Int64) Returns a value that indicates whether a BigInteger value and a 64-bit signed integer are not equal.
Public operatorStatic member Inequality(BigInteger, BigInteger) Returns a value that indicates whether two BigInteger objects have different values.
Public operatorStatic member Inequality(BigInteger, UInt64) Returns a value that indicates whether a BigInteger value and a 64-bit unsigned integer are not equal.
Public operatorStatic member Inequality(Int64, BigInteger) Returns a value that indicates whether a 64-bit signed integer and a BigInteger value are not equal.
Public operatorStatic member Inequality(UInt64, BigInteger) Returns a value that indicates whether a 64-bit unsigned integer and a BigInteger value are not equal.
Public operatorStatic member LeftShift Shifts a BigInteger value a specified number of bits to the left.
Public operatorStatic member LessThan(BigInteger, Int64) Returns a value that indicates whether a BigInteger value is less than a 64-bit signed integer.
Public operatorStatic member LessThan(BigInteger, BigInteger) Returns a value that indicates whether a BigInteger value is less than another BigInteger value.
Public operatorStatic member LessThan(BigInteger, UInt64) Returns a value that indicates whether a BigInteger value is less than a 64-bit unsigned integer.
Public operatorStatic member LessThan(Int64, BigInteger) Returns a value that indicates whether a 64-bit signed integer is less than a BigInteger value.
Public operatorStatic member LessThan(UInt64, BigInteger) Returns a value that indicates whether a 64-bit unsigned integer is less than a BigInteger value.
Public operatorStatic member LessThanOrEqual(BigInteger, Int64) Returns a value that indicates whether a BigInteger value is less than or equal to a 64-bit signed integer.
Public operatorStatic member LessThanOrEqual(BigInteger, BigInteger) Returns a value that indicates whether a BigInteger value is less than or equal to another BigInteger value.
Public operatorStatic member LessThanOrEqual(BigInteger, UInt64) Returns a value that indicates whether a BigInteger value is less than or equal to a 64-bit unsigned integer.
Public operatorStatic member LessThanOrEqual(Int64, BigInteger) Returns a value that indicates whether a 64-bit signed integer is less than or equal to a BigInteger value.
Public operatorStatic member LessThanOrEqual(UInt64, BigInteger) Returns a value that indicates whether a 64-bit unsigned integer is less than or equal to a BigInteger value.
Public operatorStatic member Modulus Returns the remainder that results from division with two specified BigInteger values.
Public operatorStatic member Multiply Multiplies two specified BigInteger values.
Public operatorStatic member OnesComplement Returns the bitwise one's complement of a BigInteger value.
Public operatorStatic member RightShift Shifts a BigInteger value a specified number of bits to the right.
Public operatorStatic member Subtraction Subtracts a BigInteger value from another BigInteger value.
Public operatorStatic member UnaryNegation Negates a specified BigInteger value.
Public operatorStatic member UnaryPlus Returns the value of the BigInteger operand. (The sign of the operand is unchanged.)

Top

Remarks

The BigInteger type is an immutable type that represents an arbitrarily large integer whose value in theory has no upper or lower bounds. The members of the BigInteger type closely parallel those of other integral types (the Byte, Int16, Int32, Int64, SByte, UInt16, UInt32, and UInt64 types). This type differs from the other integral types in the .NET Framework, which have a range indicated by their MinValue and MaxValue properties.

NoteNote:

Because the BigInteger type is immutable (see Mutability and the BigInteger Structure) and because it has no upper or lower bounds, an OutOfMemoryException can be thrown for any operation that causes a BigInteger value to grow too large.

Instantiating a BigInteger Object

You can instantiate a BigInteger object in several ways:

  • You can use the new keyword and provide any integral or floating-point value as a parameter to the BigInteger constructor. (Floating-point values are truncated before they are assigned to the BigInteger.) The following example illustrates how to use the new keyword to instantiate BigInteger values.

    Dim bigIntFromDouble As New BigInteger(179032.6541)
    outputBlock.Text += bigIntFromDouble.ToString() + vbCrLf
    Dim bigIntFromInt64 As New BigInteger(934157136952)
    outputBlock.Text += bigIntFromInt64.ToString() + vbCrLf
    ' The example displays the following output:
    '   179032
    '   934157136952        
    
    BigInteger bigIntFromDouble = new BigInteger(179032.6541);
    outputBlock.Text += bigIntFromDouble + "\n";
    BigInteger bigIntFromInt64 = new BigInteger(934157136952);
    outputBlock.Text += bigIntFromInt64 + "\n";
    // The example displays the following output:
    //   179032
    //   934157136952       
    
  • You can declare a BigInteger variable and assign it a value just as you would any numeric type, as long as that value is an integral type. The following example uses assignment to create a BigInteger value from an Int64.

    Dim longValue As Long = 6315489358112
    Dim assignedFromLong As BigInteger = longValue
    outputBlock.Text += assignedFromLong.ToString() + vbCrLf
    ' The example displays the following output:
    '   6315489358112
    
    long longValue = 6315489358112;
    BigInteger assignedFromLong = longValue;
    outputBlock.Text += assignedFromLong + "\n";
    // The example displays the following output:
    //   6315489358112
    
  • You can assign a decimal or floating-point value to a BigInteger object if you cast the value or convert it first. The following example explicitly casts (in C#) or converts (in Visual Basic) a Double and a Decimal value to a BigInteger.

    Dim assignedFromDouble As BigInteger = CType(179032.6541, BigInteger)
    outputBlock.Text += assignedFromDouble.ToString() + vbCrLf
    Dim assignedFromDecimal As BigInteger = CType(64312.65D, BigInteger)
    outputBlock.Text += assignedFromDecimal.ToString() + vbCrLf
    ' The example displays the following output:
    '   179032
    '   64312      
    
    BigInteger assignedFromDouble = (BigInteger)179032.6541;
    outputBlock.Text += assignedFromDouble + "\n";
    BigInteger assignedFromDecimal = (BigInteger)64312.65m;
    outputBlock.Text += assignedFromDecimal + "\n";
    // The example displays the following output:
    //   179032
    //   64312      
    

These methods enable you to instantiate a BigInteger object whose value is in the range of one of the existing numeric types only. You can instantiate a BigInteger object whose value can exceed the range of the existing numeric types in one of three ways:

  • You can use the new keyword and provide a byte array of any size to the BigInteger.BigInteger constructor. For example:

    Dim byteArray() As Byte = {10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0}
    Dim newBigInt As New BigInteger(byteArray)
    outputBlock.Text += String.Format("The value of newBigInt is {0} (or 0x{0:x}).", newBigInt) & vbCrLf
    ' The example displays the following output:
    '   The value of newBigInt is 4759477275222530853130 (or 0x102030405060708090a).
    
    byte[] byteArray = { 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0 };
    BigInteger newBigInt = new BigInteger(byteArray);
    outputBlock.Text += String.Format("The value of newBigInt is {0} (or 0x{0:x}).", newBigInt) + "\n";
    // The example displays the following output:
    //   The value of newBigInt is 4759477275222530853130 (or 0x102030405060708090a).
    
  • You can call a static (Shared in Visual Basic) BigInteger method that performs some operation on a numeric expression and returns a calculated BigInteger result. The following example does this by cubing UInt64.MaxValue and assigning the result to a BigInteger.

    Dim number As BigInteger = BigInteger.Pow(UInt64.MaxValue, 3)
    outputBlock.Text += number.ToString() + vbCrLf
    ' The example displays the following output:
    '    6277101735386680762814942322444851025767571854389858533375
    
    BigInteger number = BigInteger.Pow(UInt64.MaxValue, 3);
    outputBlock.Text += number + "\n";
    // The example displays the following output:
    //    6277101735386680762814942322444851025767571854389858533375
    

The uninitialized value of a BigInteger is Zero.

Performing Operations on BigInteger Values

You can use a BigInteger instance as you would use any other integral type. BigInteger overloads the standard numeric operators to enable you to perform basic mathematical operations such as addition, subtraction, division, multiplication, subtraction, negation, and unary negation. You can also use the standard numeric operators to compare two BigInteger values with each other. Like the other integral types, BigInteger also supports the bitwise And, Or, XOr, left shift, and right shift operators. For languages that do not support custom operators, the BigInteger structure also provides equivalent methods for performing mathematical operations. These include Add, Divide, Multiply, Negate, Subtract, and several others.

Many members of the BigInteger structure correspond directly to members of the other integral types. In addition, BigInteger adds members such as the following:

  • Sign, which returns a value that indicates the sign of a BigInteger value.

  • Abs, which returns the absolute value of a BigInteger value.

  • DivRem, which returns both the quotient and remainder of a division operation.

  • GreatestCommonDivisor, which returns the greatest common divisor of two BigInteger values.

Many of these additional members correspond to the members of the Math class, which provides the functionality to work with the primitive numeric types.

Mutability and the BigInteger Structure

The following example instantiates a BigInteger object and then increments its value by one.

Dim number As BigInteger = BigInteger.Multiply(Int64.MaxValue, 3)
number += 1
outputBlock.Text &= number.ToString() + vbCrLf
BigInteger number = BigInteger.Multiply(Int64.MaxValue, 3);
number++;
outputBlock.Text += number + "\n";

Although this example appears to modify the value of the existing object, this is not the case. BigInteger objects are immutable, which means that internally, the common language runtime actually creates a new BigInteger object and assigns it a value one greater than its previous value. This new object is then returned to the caller.

NoteNote:

The other numeric types in the .NET Framework are also immutable. However, because the BigInteger type has no upper or lower bounds, its values can grow extremely large and have a measurable impact on performance.

Although this process is transparent to the caller, it does incur a performance penalty. In some cases, especially when repeated operations are performed in a loop on very large BigInteger values, that performance penalty can be significant. For example, in the following example, an operation is performed repetitively up to a million times, and a BigInteger value is incremented by one every time the operation succeeds.

Dim number As BigInteger = Int64.MaxValue ^ 5
Dim repetitions As Integer = 1000000
' Perform some repetitive operation 1 million times.
For ctr As Integer = 0 To repetitions
   ' Perform some operation. If it fails, exit the loop.
   If Not SomeOperationSucceeds() Then Exit For
   ' The following code executes if the operation succeeds.
   number += 1
Next
BigInteger number = Int64.MaxValue ^ 5;
int repetitions = 1000000;
// Perform some repetitive operation 1 million times.
for (int ctr = 0; ctr <= repetitions; ctr++)
{
   // Perform some operation. If it fails, exit the loop.
   if (!SomeOperationSucceeds()) break;
   // The following code executes if the operation succeeds.
   number++;
}

In such a case, you can improve performance by performing all intermediate assignments to an Int32 variable. The final value of the variable can then be assigned to the BigInteger object when the loop exits. The following example provides an illustration.

Dim number As BigInteger = Int64.MaxValue ^ 5
Dim repetitions As Integer = 1000000
Dim actualRepetitions As Integer = 0
' Perform some repetitive operation 1 million times.
For ctr As Integer = 0 To repetitions
   ' Perform some operation. If it fails, exit the loop.
   If Not SomeOperationSucceeds() Then Exit For
   ' The following code executes if the operation succeeds.
   actualRepetitions += 1
Next
number += actualRepetitions
BigInteger number = Int64.MaxValue ^ 5;
int repetitions = 1000000;
int actualRepetitions = 0;
// Perform some repetitive operation 1 million times.
for (int ctr = 0; ctr <= repetitions; ctr++)
{
   // Perform some operation. If it fails, exit the loop.
   if (!SomeOperationSucceeds()) break;
   // The following code executes if the operation succeeds.
   actualRepetitions++;
}
number += actualRepetitions;

Working with Byte Arrays and Hexadecimal Strings

If you convert BigInteger values to byte arrays, or if you convert byte arrays to BigInteger values, you must consider the order of bytes. The BigInteger structure expects the individual bytes in a byte array to appear in little-endian order (that is, the lower-order bytes of the value precede the higher-order bytes). You can round-trip a BigInteger value by calling the ToByteArray method and then passing the resulting byte array to the BigInteger(array<Byte[]) constructor, as the following example shows.

Dim number As BigInteger = BigInteger.Pow(Int64.MaxValue, 2)
outputBlock.Text &= number.ToString() & vbCrLf

' Write the BigInteger value to a byte array.
Dim bytes() As Byte = number.ToByteArray()

' Display the byte array.
For Each byteValue As Byte In bytes
   outputBlock.Text += String.Format("0x{0:X2} ", byteValue)
Next
outputBlock.Text &= vbCrLf

' Restore the BigInteger value from a Byte array.
Dim newNumber As BigInteger = New BigInteger(bytes)
outputBlock.Text &= newNumber.ToString() & vbCrLf
' The example displays the following output:
'    8.5070591730234615847396907784E+37
'    0x01 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0x3F
'    
'    8.5070591730234615847396907784E+37
BigInteger number = BigInteger.Pow(Int64.MaxValue, 2);
outputBlock.Text += number + "\n";

// Write the BigInteger value to a byte array.
byte[] bytes = number.ToByteArray();

// Display the byte array.
foreach (byte byteValue in bytes)
   outputBlock.Text += String.Format("0x{0:X2} ", byteValue);
outputBlock.Text += "\n";

// Restore the BigInteger value from a Byte array.
BigInteger newNumber = new BigInteger(bytes);
outputBlock.Text += newNumber + "\n";
// The example displays the following output:
//    8.5070591730234615847396907784E+37
//    0x01 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0x3F
//    
//    8.5070591730234615847396907784E+37

To instantiate a BigInteger value from a byte array that represents a value of some other integral type, you can pass the integral value to the BitConverter.GetBytes method, and then pass the resulting byte array to the BigInteger(array<Byte[]) constructor. The following example instantiates a BigInteger value from a byte array that represents an Int16 value.

Dim originalValue As Short = 30000
outputBlock.Text &= originalValue & vbCrLf

' Convert the Int16 value to a byte array.
Dim bytes() As Byte = BitConverter.GetBytes(originalValue)

' Display the byte array.
For Each byteValue As Byte In bytes
   outputBlock.Text += String.Format("0x{0} ", byteValue.ToString("X2"))
Next
outputBlock.Text &= vbCrLf

' Pass byte array to the BigInteger constructor.
Dim number As BigInteger = New BigInteger(bytes)
outputBlock.Text &= number.ToString() & vbCrLf
' The example displays the following output:
'       30000
'       0x30 0x75
'       30000
short originalValue = 30000;
outputBlock.Text += originalValue + "\n";

// Convert the Int16 value to a byte array.
byte[] bytes = BitConverter.GetBytes(originalValue);

// Display the byte array.
foreach (byte byteValue in bytes)
   outputBlock.Text += String.Format("0x{0} ", byteValue.ToString("X2"));
outputBlock.Text += "\n";

// Pass byte array to the BigInteger constructor.
BigInteger number = new BigInteger(bytes);
outputBlock.Text += number + "\n";
// The example displays the following output:
//       30000
//       0x30 0x75
//       30000

The BigInteger structure assumes that negative values are stored by using two's complement representation. Because the BigInteger structure represents a numeric value with no fixed length, the BigInteger(array<Byte[]) constructor always interprets the most significant bit of the last byte in the array as a sign bit. To prevent the BigInteger(array<Byte[]) constructor from confusing the two's complement representation of a negative value with the sign and magnitude representation of a positive value, positive values in which the most significant bit of the last byte in the byte array would ordinarily be set should include an additional byte whose value is 0. For example, 0xC0 0xBD 0xF0 0xFF is the little-endian hexadecimal representation of either -1,000,000 or 4,293,967,296. Because the most significant bit of the last byte in this array is on, the value of the byte array would be interpreted by the BigInteger(array<Byte[]) constructor as -1,000,000. To instantiate a BigInteger whose value is positive, a byte array whose elements are 0xC0 0xBD 0xF0 0xFF 0x00 must be passed to the constructor. The following example illustrates this.

Dim negativeNumber As Integer = -1000000
Dim positiveNumber As UInteger = 4293967296

Dim negativeBytes() As Byte = BitConverter.GetBytes(negativeNumber)
Dim negativeBigInt As New BigInteger(negativeBytes)
outputBlock.Text &= negativeBigInt.ToString() & vbCrLf

Dim tempPosBytes() As Byte = BitConverter.GetBytes(positiveNumber)
Dim positiveBytes(tempPosBytes.Length) As Byte
Array.Copy(tempPosBytes, positiveBytes, tempPosBytes.Length)
Dim positiveBigInt As New BigInteger(positiveBytes)
outputBlock.Text &= positiveBigInt.ToString() & vbCrLf
' The example displays the following output:
'    -1000000
'    4293967296      
int negativeNumber = -1000000;
uint positiveNumber = 4293967296;

byte[] negativeBytes = BitConverter.GetBytes(negativeNumber);
BigInteger negativeBigInt = new BigInteger(negativeBytes);
outputBlock.Text += negativeBigInt.ToString() + "\n";

byte[] tempPosBytes = BitConverter.GetBytes(positiveNumber);
byte[] positiveBytes = new byte[tempPosBytes.Length + 1];
Array.Copy(tempPosBytes, positiveBytes, tempPosBytes.Length);
BigInteger positiveBigInt = new BigInteger(positiveBytes);
outputBlock.Text += positiveBigInt.ToString() + "\n";
// The example displays the following output:
//    -1000000
//    4293967296      

Byte arrays created by the ToByteArray method from positive values include this extra zero-value byte. Therefore, the BigInteger structure can successfully round-trip values by assigning them to, and then restoring them from, byte arrays, as the following example shows.

Dim positiveValue As BigInteger = 15777216
Dim negativeValue As BigInteger = -1000000

outputBlock.Text &= "Positive value: " + positiveValue.ToString() & vbCrLf
Dim bytes() As Byte = positiveValue.ToByteArray()
For Each byteValue As Byte In bytes
   outputBlock.Text += String.Format("{0:X2} ", byteValue)
Next
outputBlock.Text &= vbCrLf
positiveValue = New BigInteger(bytes)
outputBlock.Text &= "Restored positive value: " + positiveValue.ToString() & vbCrLf

outputBlock.Text &= vbCrLf

outputBlock.Text &= "Negative value: " + negativeValue.ToString() & vbCrLf
bytes = negativeValue.ToByteArray()
For Each byteValue As Byte In bytes
   outputBlock.Text += String.Format("{0:X2} ", byteValue)
Next
outputBlock.Text &= vbCrLf
negativeValue = New BigInteger(bytes)
outputBlock.Text &= "Restored negative value: " + negativeValue.ToString() & vbCrLf
' The example displays the following output:
'       Positive value: 15777216
'       C0 BD F0 00
'       Restored positive value: 15777216
'       
'       Negative value: -1000000
'       C0 BD F0
'       Restored negative value: -1000000
BigInteger positiveValue = 15777216;
BigInteger negativeValue = -1000000;

outputBlock.Text += "Positive value: " + positiveValue.ToString() + "\n";
byte[] bytes = positiveValue.ToByteArray();

foreach (byte byteValue in bytes)
   outputBlock.Text += String.Format("{0:X2} ", byteValue);
outputBlock.Text += "\n";
positiveValue = new BigInteger(bytes);
outputBlock.Text += "Restored positive value: " + positiveValue.ToString() + "\n";

outputBlock.Text += "\n";

outputBlock.Text += "Negative value: " + negativeValue.ToString() + "\n";
bytes = negativeValue.ToByteArray();
foreach (byte byteValue in bytes)
   outputBlock.Text += String.Format("{0:X2} ", byteValue);
outputBlock.Text += "\n";
negativeValue = new BigInteger(bytes);
outputBlock.Text += "Restored negative value: " + negativeValue.ToString() + "\n";
// The example displays the following output:
//       Positive value: 15777216
//       C0 BD F0 00
//       Restored positive value: 15777216
//       
//       Negative value: -1000000
//       C0 BD F0
//       Restored negative value: -1000000

However, you may need to add this additional zero-value byte to byte arrays that are created dynamically by the developer or that are returned by methods that convert unsigned integers to byte arrays (such as BitConverter.GetBytes(UInt16), BitConverter.GetBytes(UInt32), and BitConverter.GetBytes(UInt64)).

Version Information

Silverlight

Supported in: 5, 4

Platforms

For a list of the operating systems and browsers that are supported by Silverlight, see Supported Operating Systems and Browsers.

Thread Safety

Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.

See Also

Reference