Struct System.Numerics.BigInteger

Questo articolo fornisce osservazioni supplementari alla documentazione di riferimento per questa API.

Il BigInteger tipo è un tipo non modificabile che rappresenta un intero arbitrariamente grande il cui valore in teoria non ha limiti superiori o inferiori. I membri del BigInteger tipo paralleli strettamente quelli di altri tipi integrali (i Bytetipi , SByteInt64Int32UInt16Int16UInt32e ).UInt64 Questo tipo è diverso dagli altri tipi integrali in .NET, che hanno un intervallo indicato dalle relative MinValue proprietà e MaxValue .

Nota

Poiché il BigInteger tipo non è modificabile (vedere Mutabilità) e poiché non dispone di limiti superiori o inferiori, è possibile generare un'eccezione OutOfMemoryException per qualsiasi operazione che causa un aumento eccessivo di un BigInteger valore.

Creare un'istanza di un oggetto BigInteger

È possibile creare un'istanza di un BigInteger oggetto in diversi modi:

  • È possibile usare la new parola chiave e specificare qualsiasi valore integrale o a virgola mobile come parametro per il BigInteger costruttore. I valori a virgola mobile vengono troncati prima che vengano assegnati a BigInteger. Nell'esempio seguente viene illustrato come usare la parola chiave per creare un'istanza new dei BigInteger valori.

    BigInteger bigIntFromDouble = new BigInteger(179032.6541);
    Console.WriteLine(bigIntFromDouble);
    BigInteger bigIntFromInt64 = new BigInteger(934157136952);
    Console.WriteLine(bigIntFromInt64);
    // The example displays the following output:
    //   179032
    //   934157136952
    
    Dim bigIntFromDouble As New BigInteger(179032.6541)
    Console.WriteLine(bigIntFromDouble)
    Dim bigIntFromInt64 As New BigInteger(934157136952)
    Console.WriteLine(bigIntFromInt64)
    ' The example displays the following output:
    '   179032
    '   934157136952
    
  • È possibile dichiarare una BigInteger variabile e assegnarla un valore esattamente come qualsiasi tipo numerico, purché tale valore sia un tipo integrale. Nell'esempio seguente viene usata l'assegnazione per creare un BigInteger valore da un oggetto Int64.

    long longValue = 6315489358112;
    BigInteger assignedFromLong = longValue;
    Console.WriteLine(assignedFromLong);
    // The example displays the following output:
    //   6315489358112
    
    Dim longValue As Long = 6315489358112
    Dim assignedFromLong As BigInteger = longValue
    Console.WriteLine(assignedFromLong)
    ' The example displays the following output:
    '   6315489358112
    
  • È possibile assegnare un valore decimale o a virgola mobile a un BigInteger oggetto se si esegue il cast del valore o lo si converte per primo. Nell'esempio seguente viene eseguito il cast esplicito (in C#) o la conversione (in Visual Basic) di e Double un Decimal valore in un oggetto BigInteger.

    BigInteger assignedFromDouble = (BigInteger) 179032.6541;
    Console.WriteLine(assignedFromDouble);
    BigInteger assignedFromDecimal = (BigInteger) 64312.65m;
    Console.WriteLine(assignedFromDecimal);
    // The example displays the following output:
    //   179032
    //   64312
    
    Dim assignedFromDouble As BigInteger = CType(179032.6541, BigInteger)
    Console.WriteLine(assignedFromDouble)
    Dim assignedFromDecimal As BigInteger = CType(64312.65D, BigInteger)
    Console.WriteLine(assignedFromDecimal)
    ' The example displays the following output:
    '   179032
    '   64312
    

Questi metodi consentono di creare un'istanza di un BigInteger oggetto il cui valore si trova nell'intervallo di uno dei tipi numerici esistenti. È possibile creare un'istanza di un BigInteger oggetto il cui valore può superare l'intervallo dei tipi numerici esistenti in uno dei tre modi seguenti:

  • È possibile usare la new parola chiave e fornire una matrice di byte di qualsiasi dimensione al BigInteger.BigInteger costruttore. Ad esempio:

    byte[] byteArray = { 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0};
    BigInteger newBigInt = new BigInteger(byteArray);
    Console.WriteLine("The value of newBigInt is {0} (or 0x{0:x}).", newBigInt);
    // The example displays the following output:
    //   The value of newBigInt is 4759477275222530853130 (or 0x102030405060708090a).
    
    Dim byteArray() As Byte = {10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0}
    Dim newBigInt As New BigInteger(byteArray)
    Console.WriteLine("The value of newBigInt is {0} (or 0x{0:x}).", newBigInt)
    ' The example displays the following output:
    '   The value of newBigInt is 4759477275222530853130 (or 0x102030405060708090a).
    
  • È possibile chiamare i Parse metodi o TryParse per convertire la rappresentazione di stringa di un numero in un oggetto BigInteger. Ad esempio:

    string positiveString = "91389681247993671255432112000000";
    string negativeString = "-90315837410896312071002088037140000";
    BigInteger posBigInt = 0;
    BigInteger negBigInt = 0;
    
    try {
       posBigInt = BigInteger.Parse(positiveString);
       Console.WriteLine(posBigInt);
    }
    catch (FormatException)
    {
       Console.WriteLine("Unable to convert the string '{0}' to a BigInteger value.",
                         positiveString);
    }
    
    if (BigInteger.TryParse(negativeString, out negBigInt))
      Console.WriteLine(negBigInt);
    else
       Console.WriteLine("Unable to convert the string '{0}' to a BigInteger value.",
                          negativeString);
    
    // The example displays the following output:
    //   9.1389681247993671255432112E+31
    //   -9.0315837410896312071002088037E+34
    
    Dim positiveString As String = "91389681247993671255432112000000"
    Dim negativeString As String = "-90315837410896312071002088037140000"
    Dim posBigInt As BigInteger = 0
    Dim negBigInt As BigInteger = 0
    
    Try
        posBigInt = BigInteger.Parse(positiveString)
        Console.WriteLine(posBigInt)
    Catch e As FormatException
        Console.WriteLine("Unable to convert the string '{0}' to a BigInteger value.",
                          positiveString)
    End Try
    
    If BigInteger.TryParse(negativeString, negBigInt) Then
        Console.WriteLine(negBigInt)
    Else
        Console.WriteLine("Unable to convert the string '{0}' to a BigInteger value.",
                           negativeString)
    End If
    ' The example displays the following output:
    '   9.1389681247993671255432112E+31
    '   -9.0315837410896312071002088037E+34
    
  • È possibile chiamare un static metodo (Shared in Visual Basic) BigInteger che esegue un'operazione su un'espressione numerica e restituisce un risultato calcolato BigInteger . L'esempio seguente esegue questa operazione cubindo UInt64.MaxValue e assegnando il risultato a un oggetto BigInteger.

    BigInteger number = BigInteger.Pow(UInt64.MaxValue, 3);
    Console.WriteLine(number);
    // The example displays the following output:
    //    6277101735386680762814942322444851025767571854389858533375
    
    Dim number As BigInteger = BigInteger.Pow(UInt64.MaxValue, 3)
    Console.WriteLine(number)
    ' The example displays the following output:
    ' 6277101735386680762814942322444851025767571854389858533375
    

Il valore non inizializzato di un BigInteger oggetto è Zero.

Eseguire operazioni sui valori BigInteger

È possibile usare un'istanza BigInteger di come si userebbe qualsiasi altro tipo integrale. BigInteger esegue l'overload degli operatori numerici standard per consentire di eseguire operazioni matematiche di base, ad esempio addizione, sottrazione, divisione, moltiplicazione e negazione unaria. È anche possibile usare gli operatori numerici standard per confrontare due BigInteger valori tra loro. Analogamente agli altri tipi integrali, BigInteger supporta anche gli operatori bit per Andbit , Or, XOrmaiusc a sinistra e di spostamento a destra. Per i linguaggi che non supportano operatori personalizzati, la BigInteger struttura fornisce anche metodi equivalenti per l'esecuzione di operazioni matematiche. Sono inclusi Add, DivideMultiply, Negate, , Subtracte diversi altri.

Molti membri della BigInteger struttura corrispondono direttamente ai membri degli altri tipi integrali. Aggiunge inoltre BigInteger membri come i seguenti:

  • Sign, che restituisce un valore che indica il segno di un BigInteger valore.

  • Abs, che restituisce il valore assoluto di un BigInteger valore.

  • DivRem, che restituisce sia il quoziente che il resto di un'operazione di divisione.

  • GreatestCommonDivisor, che restituisce il divisore comune più grande di due BigInteger valori.

Molti di questi membri aggiuntivi corrispondono ai membri della Math classe , che fornisce la funzionalità per lavorare con i tipi numerici primitivi.

Modificabilità

Nell'esempio seguente viene creata un'istanza di un BigInteger oggetto e quindi ne viene incrementato il valore di uno.

BigInteger number = BigInteger.Multiply(Int64.MaxValue, 3);
number++;
Console.WriteLine(number);
Dim number As BigInteger = BigInteger.Multiply(Int64.MaxValue, 3)
number += 1
Console.WriteLine(number)

Anche se questo esempio sembra modificare il valore dell'oggetto esistente, questo non è il caso. BigInteger gli oggetti non sono modificabili, ovvero internamente, Common Language Runtime crea effettivamente un nuovo BigInteger oggetto e lo assegna un valore maggiore del valore precedente. Questo nuovo oggetto viene quindi restituito al chiamante.

Nota

Anche gli altri tipi numerici in .NET sono non modificabili. Tuttavia, poiché il BigInteger tipo non ha limiti superiori o inferiori, i relativi valori possono aumentare estremamente grandi e avere un impatto misurabile sulle prestazioni.

Anche se questo processo è trasparente per il chiamante, comporta una riduzione delle prestazioni. In alcuni casi, soprattutto quando le operazioni ripetute vengono eseguite in un ciclo su valori molto grandi BigInteger , la riduzione delle prestazioni può essere significativa. Nell'esempio seguente, ad esempio, un'operazione viene eseguita ripetutamente fino a un milione di volte e un BigInteger valore viene incrementato di uno ogni volta che l'operazione ha esito positivo.

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++;
}
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

In questo caso, è possibile migliorare le prestazioni eseguendo tutte le assegnazioni intermedie a una Int32 variabile. Il valore finale della variabile può quindi essere assegnato all'oggetto BigInteger quando il ciclo viene chiuso. Di seguito ne viene illustrato un esempio.

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;
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

Matrici di byte e stringhe esadecimali

Se si converte BigInteger valori in matrici di byte o si converteno matrici di byte in BigInteger valori, è necessario considerare l'ordine dei byte. La BigInteger struttura prevede che i singoli byte in una matrice di byte vengano visualizzati in ordine little-endian, ovvero i byte di ordine inferiore del valore precedono i byte di ordine superiore. È possibile eseguire il round trip di un BigInteger valore chiamando il ToByteArray metodo e quindi passando la matrice di byte risultante al BigInteger(Byte[]) costruttore, come illustrato nell'esempio seguente.

BigInteger number = BigInteger.Pow(Int64.MaxValue, 2);
Console.WriteLine(number);

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

// Display the byte array.
foreach (byte byteValue in bytes)
    Console.Write("0x{0:X2} ", byteValue);
Console.WriteLine();

// Restore the BigInteger value from a Byte array.
BigInteger newNumber = new BigInteger(bytes);
Console.WriteLine(newNumber);
// 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
Dim number As BigInteger = BigInteger.Pow(Int64.MaxValue, 2)     
Console.WriteLine(number)

' 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
   Console.Write("0x{0:X2} ", byteValue)
Next   
Console.WriteLine()

' Restore the BigInteger value from a Byte array.
Dim newNumber As BigInteger = New BigInteger(bytes)
Console.WriteLine(newNumber)               
' 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

Per creare un'istanza di un BigInteger valore da una matrice di byte che rappresenta un valore di un altro tipo integrale, è possibile passare il valore integrale al BitConverter.GetBytes metodo e quindi passare la matrice di byte risultante al BigInteger(Byte[]) costruttore. Nell'esempio seguente viene creata un'istanza di un BigInteger valore da una matrice di byte che rappresenta un Int16 valore.

short originalValue = 30000;
Console.WriteLine(originalValue);

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

// Display the byte array.
foreach (byte byteValue in bytes)
    Console.Write("0x{0} ", byteValue.ToString("X2"));
Console.WriteLine();

// Pass byte array to the BigInteger constructor.
BigInteger number = new BigInteger(bytes);
Console.WriteLine(number);
// The example displays the following output:
//       30000
//       0x30 0x75
//       30000
Dim originalValue As Short = 30000
Console.WriteLine(originalValue)

' 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
   Console.Write("0x{0} ", byteValue.ToString("X2"))
Next    
Console.WriteLine() 

' Pass byte array to the BigInteger constructor.
Dim number As BigInteger = New BigInteger(bytes)
Console.WriteLine(number)
' The example displays the following output:
'       30000
'       0x30 0x75
'       30000

La BigInteger struttura presuppone che i valori negativi vengano archiviati usando la rappresentazione di complemento di due. Poiché la BigInteger struttura rappresenta un valore numerico senza lunghezza fissa, il BigInteger(Byte[]) costruttore interpreta sempre il bit più significativo dell'ultimo byte nella matrice come bit di segno. Per evitare che il BigInteger(Byte[]) costruttore confonda la rappresentazione di complemento di un valore negativo con il segno e la rappresentazione di grandezza di un valore positivo, i valori positivi in cui il bit più significativo dell'ultimo byte nella matrice di byte deve in genere essere impostato deve includere un byte aggiuntivo il cui valore è 0. Ad esempio, 0xC0 0xBD 0xF0 0xFF è la rappresentazione esadecimale little-endian di -1.000.000 o 4.293.967.296. Poiché il bit più significativo dell'ultimo byte in questa matrice è attivo, il valore della matrice di byte verrebbe interpretato dal BigInteger(Byte[]) costruttore come -1.000.000. Per creare un'istanza di un BigInteger oggetto il cui valore è positivo, è necessario passare al costruttore una matrice di byte i cui elementi sono 0xC0 0xBD 0xF0 0xFF 0x00. Ciò è illustrato nell'esempio seguente.

int negativeNumber = -1000000;
uint positiveNumber = 4293967296;

byte[] negativeBytes = BitConverter.GetBytes(negativeNumber);
BigInteger negativeBigInt = new BigInteger(negativeBytes);
Console.WriteLine(negativeBigInt.ToString("N0"));

byte[] tempPosBytes = BitConverter.GetBytes(positiveNumber);
byte[] positiveBytes = new byte[tempPosBytes.Length + 1];
Array.Copy(tempPosBytes, positiveBytes, tempPosBytes.Length);
BigInteger positiveBigInt = new BigInteger(positiveBytes);
Console.WriteLine(positiveBigInt.ToString("N0"));
// The example displays the following output:
//    -1,000,000
//    4,293,967,296
Dim negativeNumber As Integer = -1000000
Dim positiveNumber As UInteger = 4293967296

Dim negativeBytes() As Byte = BitConverter.GetBytes(negativeNumber) 
Dim negativeBigInt As New BigInteger(negativeBytes)
Console.WriteLine(negativeBigInt.ToString("N0"))

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)
Console.WriteLine(positiveBigInt.ToString("N0")) 
' The example displays the following output:
'    -1,000,000
'    4,293,967,296

Le matrici di byte create dal metodo da ToByteArray valori positivi includono questo byte con valore zero aggiuntivo. Pertanto, la struttura può eseguire correttamente il BigInteger round trip assegnandoli a e quindi ripristinandoli da matrici di byte, come illustrato nell'esempio seguente.

BigInteger positiveValue = 15777216;
BigInteger negativeValue = -1000000;

Console.WriteLine("Positive value: " + positiveValue.ToString("N0"));
byte[] bytes = positiveValue.ToByteArray();

foreach (byte byteValue in bytes)
    Console.Write("{0:X2} ", byteValue);
Console.WriteLine();
positiveValue = new BigInteger(bytes);
Console.WriteLine("Restored positive value: " + positiveValue.ToString("N0"));

Console.WriteLine();

Console.WriteLine("Negative value: " + negativeValue.ToString("N0"));
bytes = negativeValue.ToByteArray();
foreach (byte byteValue in bytes)
    Console.Write("{0:X2} ", byteValue);
Console.WriteLine();
negativeValue = new BigInteger(bytes);
Console.WriteLine("Restored negative value: " + negativeValue.ToString("N0"));
// The example displays the following output:
//       Positive value: 15,777,216
//       C0 BD F0 00
//       Restored positive value: 15,777,216
//
//       Negative value: -1,000,000
//       C0 BD F0
//       Restored negative value: -1,000,000
Dim positiveValue As BigInteger = 15777216
Dim negativeValue As BigInteger = -1000000

Console.WriteLine("Positive value: " + positiveValue.ToString("N0"))
Dim bytes() As Byte = positiveValue.ToByteArray()
For Each byteValue As Byte In bytes
   Console.Write("{0:X2} ", byteValue)
Next
Console.WriteLine()
positiveValue = New BigInteger(bytes)
Console.WriteLine("Restored positive value: " + positiveValue.ToString("N0"))

Console.WriteLine()
   
Console.WriteLIne("Negative value: " + negativeValue.ToString("N0"))
bytes = negativeValue.ToByteArray()
For Each byteValue As Byte In bytes
   Console.Write("{0:X2} ", byteValue)
Next
Console.WriteLine()
negativeValue = New BigInteger(bytes)
Console.WriteLine("Restored negative value: " + negativeValue.ToString("N0"))
' The example displays the following output:
'       Positive value: 15,777,216
'       C0 BD F0 00
'       Restored positive value: 15,777,216
'       
'       Negative value: -1,000,000
'       C0 BD F0
'       Restored negative value: -1,000,000

Potrebbe tuttavia essere necessario aggiungere questo byte zero aggiuntivo alle matrici di byte create dinamicamente dallo sviluppatore o restituite da metodi che convertono numeri interi senza segno in matrici di byte , ad esempio BitConverter.GetBytes(UInt16), BitConverter.GetBytes(UInt32)e BitConverter.GetBytes(UInt64).

Quando si analizza una stringa esadecimale, i BigInteger.Parse(String, NumberStyles) metodi e BigInteger.Parse(String, NumberStyles, IFormatProvider) presuppongono che se viene impostato il bit più significativo del primo byte nella stringa o se la prima cifra esadecimale della stringa rappresenta i quattro bit inferiori di un valore di byte, il valore viene rappresentato usando la rappresentazione di complemento di due. Ad esempio, sia "FF01" che "F01" rappresentano il valore decimale -255. Per distinguere i positivi dai valori negativi, i valori positivi devono includere uno zero iniziale. Gli overload pertinenti del ToString metodo, quando vengono passati alla stringa di formato "X", aggiungere uno zero iniziale alla stringa esadecimale restituita per i valori positivi. In questo modo è possibile eseguire il round trip BigInteger dei valori usando i ToString metodi e Parse , come illustrato nell'esempio seguente.

BigInteger negativeNumber = -1000000;
BigInteger positiveNumber = 15777216;

string negativeHex = negativeNumber.ToString("X");
string positiveHex = positiveNumber.ToString("X");

BigInteger negativeNumber2, positiveNumber2;
negativeNumber2 = BigInteger.Parse(negativeHex,
                                   NumberStyles.HexNumber);
positiveNumber2 = BigInteger.Parse(positiveHex,
                                   NumberStyles.HexNumber);

Console.WriteLine("Converted {0:N0} to {1} back to {2:N0}.",
                   negativeNumber, negativeHex, negativeNumber2);
Console.WriteLine("Converted {0:N0} to {1} back to {2:N0}.",
                   positiveNumber, positiveHex, positiveNumber2);
// The example displays the following output:
//       Converted -1,000,000 to F0BDC0 back to -1,000,000.
//       Converted 15,777,216 to 0F0BDC0 back to 15,777,216.
Dim negativeNumber As BigInteger = -1000000
Dim positiveNumber As BigInteger = 15777216

Dim negativeHex As String = negativeNumber.ToString("X")
Dim positiveHex As string = positiveNumber.ToString("X")

Dim negativeNumber2, positiveNumber2 As BigInteger 
negativeNumber2 = BigInteger.Parse(negativeHex, 
                                   NumberStyles.HexNumber)
positiveNumber2 = BigInteger.Parse(positiveHex,
                                   NumberStyles.HexNumber)

Console.WriteLine("Converted {0:N0} to {1} back to {2:N0}.", 
                   negativeNumber, negativeHex, negativeNumber2)                                         
Console.WriteLine("Converted {0:N0} to {1} back to {2:N0}.", 
                   positiveNumber, positiveHex, positiveNumber2)                                         
' The example displays the following output:
'       Converted -1,000,000 to F0BDC0 back to -1,000,000.
'       Converted 15,777,216 to 0F0BDC0 back to 15,777,216.

Tuttavia, le stringhe esadecimali create chiamando i ToString metodi degli altri tipi integrali o gli overload del ToString metodo che includono un toBase parametro non indicano il segno del valore o del tipo di dati di origine da cui è stata derivata la stringa esadecimale. Per creare un'istanza di un BigInteger valore da tale stringa è necessaria una logica aggiuntiva. Nell'esempio seguente viene fornita una possibile implementazione.

using System;
using System.Globalization;
using System.Numerics;

public struct HexValue
{
    public int Sign;
    public string Value;
}

public class ByteHexExample2
{
    public static void Main()
    {
        uint positiveNumber = 4039543321;
        int negativeNumber = -255423975;

        // Convert the numbers to hex strings.
        HexValue hexValue1, hexValue2;
        hexValue1.Value = positiveNumber.ToString("X");
        hexValue1.Sign = Math.Sign(positiveNumber);

        hexValue2.Value = Convert.ToString(negativeNumber, 16);
        hexValue2.Sign = Math.Sign(negativeNumber);

        // Round-trip the hexadecimal values to BigInteger values.
        string hexString;
        BigInteger positiveBigInt, negativeBigInt;

        hexString = (hexValue1.Sign == 1 ? "0" : "") + hexValue1.Value;
        positiveBigInt = BigInteger.Parse(hexString, NumberStyles.HexNumber);
        Console.WriteLine("Converted {0} to {1} and back to {2}.",
                          positiveNumber, hexValue1.Value, positiveBigInt);

        hexString = (hexValue2.Sign == 1 ? "0" : "") + hexValue2.Value;
        negativeBigInt = BigInteger.Parse(hexString, NumberStyles.HexNumber);
        Console.WriteLine("Converted {0} to {1} and back to {2}.",
                          negativeNumber, hexValue2.Value, negativeBigInt);
    }
}
// The example displays the following output:
//       Converted 4039543321 to F0C68A19 and back to 4039543321.
//       Converted -255423975 to f0c68a19 and back to -255423975.
Imports System.Globalization
Imports System.Numerics

Public Structure HexValue
    Public Sign As Integer
    Public Value As String
End Structure

Module Example2
    Public Sub Main()
        Dim positiveNumber As UInteger = 4039543321
        Dim negativeNumber As Integer = -255423975

        ' Convert the numbers to hex strings.
        Dim hexValue1, hexValue2 As HexValue
        hexValue1.Value = positiveNumber.ToString("X")
        hexValue1.Sign = Math.Sign(positiveNumber)

        hexValue2.Value = Convert.ToString(negativeNumber, 16)
        hexValue2.Sign = Math.Sign(negativeNumber)

        ' Round-trip the hexadecimal values to BigInteger values.
        Dim hexString As String
        Dim positiveBigInt, negativeBigInt As BigInteger

        hexString = CStr(IIf(hexValue1.Sign = 1, "0", "")) + hexValue1.Value
        positiveBigInt = BigInteger.Parse(hexString, NumberStyles.HexNumber)
        Console.WriteLine("Converted {0} to {1} and back to {2}.",
                        positiveNumber, hexValue1.Value, positiveBigInt)

        hexString = CStr(IIf(hexValue2.Sign = 1, "0", "")) + hexValue2.Value
        negativeBigInt = BigInteger.Parse(hexString, NumberStyles.HexNumber)
        Console.WriteLine("Converted {0} to {1} and back to {2}.",
                        negativeNumber, hexValue2.Value, negativeBigInt)

    End Sub
End Module
' The example displays the following output:
'       Converted 4039543321 to F0C68A19 and back to 4039543321.
'       Converted -255423975 to f0c68a19 and back to -255423975.