Struct System.Numerics.BigInteger

Cet article vous offre des remarques complémentaires à la documentation de référence pour cette API.

Le BigInteger type est un type immuable qui représente un entier arbitrairement volumineux dont la valeur en théorie n’a aucune limite supérieure ou inférieure. Les membres du BigInteger type sont étroitement parallèles à ceux d’autres types intégraux (le Byte, , Int16Int32, Int64SByte, , UInt16, UInt32et UInt64 les types). Ce type diffère des autres types intégraux dans .NET, qui ont une plage indiquée par leurs propriétés et MaxValue leurs MinValue propriétés.

Remarque

Étant donné que le BigInteger type est immuable (voir Mutability) et qu’il n’a pas de limites supérieures ou inférieures, une OutOfMemoryException opération peut être levée pour toute opération qui provoque une croissance trop importante d’une BigInteger valeur.

Instancier un objet BigInteger

Vous pouvez instancier un BigInteger objet de plusieurs façons :

  • Vous pouvez utiliser le new mot clé et fournir n’importe quelle valeur intégrale ou à virgule flottante comme paramètre au BigInteger constructeur. (Les valeurs à virgule flottante sont tronquées avant qu’elles ne soient affectées au BigIntegerfichier .) L’exemple suivant montre comment utiliser le new mot clé pour instancier des BigInteger valeurs.

    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
    
  • Vous pouvez déclarer une BigInteger variable et l’affecter comme vous le feriez pour n’importe quel type numérique, tant que cette valeur est un type intégral. L’exemple suivant utilise l’affectation pour créer une BigInteger valeur à partir d’un 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
    
  • Vous pouvez affecter une valeur décimale ou à virgule flottante à un BigInteger objet si vous cassez la valeur ou convertissez-la en premier. L’exemple suivant caste explicitement (en C#) ou convertit (en Visual Basic) une Double valeur et une Decimal valeur en .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
    

Ces méthodes vous permettent d’instancier un BigInteger objet dont la valeur se trouve dans la plage d’un des types numériques existants uniquement. Vous pouvez instancier un BigInteger objet dont la valeur peut dépasser la plage des types numériques existants de l’une des trois manières suivantes :

  • Vous pouvez utiliser le new mot clé et fournir un tableau d’octets de n’importe quelle taille au BigInteger.BigInteger constructeur. Par exemple :

    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).
    
  • Vous pouvez appeler les méthodes ou TryParse les Parse méthodes pour convertir la représentation sous forme de chaîne d’un nombre en un BigInteger. Par exemple :

    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
    
  • Vous pouvez appeler une static méthode (Shared en Visual Basic) BigInteger qui effectue une opération sur une expression numérique et retourne un résultat calculé BigInteger . L’exemple suivant effectue cette opération en cubant UInt64.MaxValue et en affectant le résultat à un 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
    

La valeur non initialisée d’un BigInteger est Zero.

Effectuer des opérations sur les valeurs BigInteger

Vous pouvez utiliser une BigInteger instance comme vous l’utiliseriez n’importe quel autre type intégral. BigInteger surcharge les opérateurs numériques standard pour vous permettre d’effectuer des opérations mathématiques de base telles que l’ajout, la soustraction, la division, la multiplication et la négation unaire. Vous pouvez également utiliser les opérateurs numériques standard pour comparer deux BigInteger valeurs entre elles. Comme les autres types intégraux, BigInteger prend également en charge les opérateurs bitwise And, Or, XOrleft shift et right shift. Pour les langages qui ne prennent pas en charge les opérateurs personnalisés, la BigInteger structure fournit également des méthodes équivalentes pour effectuer des opérations mathématiques. Ceux-ci incluent Add, , DivideMultiply, Negate, Subtractet plusieurs autres.

De nombreux membres de la BigInteger structure correspondent directement aux membres des autres types intégraux. En outre, BigInteger ajoute des membres tels que les suivants :

  • Sign, qui retourne une valeur qui indique le signe d’une BigInteger valeur.

  • Abs, qui retourne la valeur absolue d’une BigInteger valeur.

  • DivRem, qui retourne à la fois le quotient et le reste d’une opération de division.

  • GreatestCommonDivisor, qui retourne le plus grand diviseur commun de deux BigInteger valeurs.

La plupart de ces membres supplémentaires correspondent aux membres de la Math classe, qui fournissent les fonctionnalités permettant d’utiliser les types numériques primitifs.

Mutabilité

L’exemple suivant instancie un BigInteger objet, puis incrémente sa valeur par un.

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)

Bien que cet exemple apparaisse pour modifier la valeur de l’objet existant, ce n’est pas le cas. BigInteger les objets sont immuables, ce qui signifie qu’en interne, le Common Language Runtime crée réellement un objet BigInteger et lui affecte une valeur supérieure à sa valeur précédente. Ce nouvel objet est ensuite retourné à l’appelant.

Remarque

Les autres types numériques dans .NET sont également immuables. Toutefois, étant donné que le BigInteger type n’a pas de limites supérieures ou inférieures, ses valeurs peuvent croître extrêmement volumineuses et avoir un impact mesurable sur les performances.

Bien que ce processus soit transparent pour l’appelant, il entraîne une pénalité de performances. Dans certains cas, en particulier lorsque des opérations répétées sont effectuées dans une boucle sur des valeurs très volumineuses BigInteger , cette pénalité de performances peut être significative. Par exemple, dans l’exemple suivant, une opération est effectuée de manière répétitive jusqu’à un million de fois, et une BigInteger valeur est incrémentée par une fois que l’opération réussit.

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

Dans ce cas, vous pouvez améliorer les performances en effectuant toutes les affectations intermédiaires à une Int32 variable. La valeur finale de la variable peut ensuite être affectée à l’objet BigInteger lorsque la boucle s’arrête. L'exemple suivant illustre cette situation.

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

Tableaux d’octets et chaînes hexadécimales

Si vous convertissez BigInteger des valeurs en tableaux d’octets ou si vous convertissez des tableaux d’octets en BigInteger valeurs, vous devez prendre en compte l’ordre des octets. La BigInteger structure s’attend à ce que les octets individuels d’un tableau d’octets apparaissent dans un ordre peu endien (autrement dit, les octets de l’ordre inférieur de la valeur précèdent les octets de l’ordre supérieur). Vous pouvez aller-retour sur une BigInteger valeur en appelant la ToByteArray méthode, puis en passant le tableau d’octets résultant au BigInteger(Byte[]) constructeur, comme l’illustre l’exemple suivant.

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

Pour instancier une BigInteger valeur à partir d’un tableau d’octets qui représente une valeur d’un autre type intégral, vous pouvez passer la valeur intégrale à la BitConverter.GetBytes méthode, puis passer le tableau d’octets résultant au BigInteger(Byte[]) constructeur. L’exemple suivant instancie une BigInteger valeur à partir d’un tableau d’octets qui représente une Int16 valeur.

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 structure suppose que les valeurs négatives sont stockées à l’aide de la représentation complète de deux. Étant donné que la BigInteger structure représente une valeur numérique sans longueur fixe, le BigInteger(Byte[]) constructeur interprète toujours le bit le plus significatif du dernier octet du tableau comme un bit de signe. Pour empêcher le BigInteger(Byte[]) constructeur de confondre la représentation complète des deux d’une valeur négative avec le signe et la représentation de magnitude d’une valeur positive, les valeurs positives dans lesquelles le bit le plus significatif du dernier octet dans le tableau d’octets serait généralement défini doit inclure un octet supplémentaire dont la valeur est 0. Par exemple, 0xC0 0xBD 0xF0 0xFF est la représentation hexadécimale peu endienne de -1 000 000 ou 4 293 967 296. Étant donné que le bit le plus significatif du dernier octet de ce tableau est activé, la valeur du tableau d’octets est interprétée par le BigInteger(Byte[]) constructeur comme -1 000 000. Pour instancier une BigInteger valeur positive, un tableau d’octets dont les éléments sont 0xC0 0xBD 0xF0 0xFF 0x00 doivent être passés au constructeur. L'exemple suivant illustre ce comportement.

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

Les tableaux d’octets créés par la ToByteArray méthode à partir de valeurs positives incluent cet octet de valeur zéro supplémentaire. Par conséquent, la BigInteger structure peut effectuer des allers-retours avec succès en les affectant, puis en les restaurant à partir de tableaux d’octets, comme l’illustre l’exemple suivant.

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

Toutefois, vous devrez peut-être ajouter cet octet de valeur zéro supplémentaire aux tableaux d’octets créés dynamiquement par le développeur ou retournés par des méthodes qui convertissent des entiers non signés en tableaux d’octets (tels que BitConverter.GetBytes(UInt16), BitConverter.GetBytes(UInt32)et BitConverter.GetBytes(UInt64)).

Lors de l’analyse d’une chaîne hexadécimale, les BigInteger.Parse(String, NumberStyles)BigInteger.Parse(String, NumberStyles, IFormatProvider) méthodes supposent que si le bit le plus significatif du premier octet de la chaîne est défini ou si le premier chiffre hexadécimal de la chaîne représente les quatre bits inférieurs d’une valeur d’octet, la valeur est représentée à l’aide de la représentation complète de deux. Par exemple, « FF01 » et « F01 » représentent la valeur décimale -255. Pour différencier les valeurs positives des valeurs négatives, les valeurs positives doivent inclure un zéro non significatif. Les surcharges pertinentes de la ToString méthode, lorsqu’elles sont passées à la chaîne de format « X », ajoutent un zéro de début à la chaîne hexadécimale retournée pour les valeurs positives. Cela permet d’aller-retour BigInteger sur les valeurs à l’aide des méthodes et Parse des ToString méthodes, comme l’illustre l’exemple suivant.

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.

Toutefois, les chaînes hexadécimales créées en appelant les ToString méthodes des autres types intégraux ou les surcharges de la ToString méthode qui incluent un toBase paramètre n’indiquent pas le signe de la valeur ou du type de données source à partir duquel la chaîne hexadécimale a été dérivée. L’instanciation réussie d’une BigInteger valeur à partir d’une telle chaîne nécessite une logique supplémentaire. L’exemple suivant fournit une implémentation possible.

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.