Estructura System.Numerics.BigInteger

En este artículo se proporcionan comentarios adicionales a la documentación de referencia de esta API.

El BigInteger tipo es un tipo inmutable que representa un entero arbitrariamente grande cuyo valor en teoría no tiene límites superiores o inferiores. Los miembros del BigInteger tipo estrechamente paralelos a los de otros tipos enteros (los Bytetipos , UInt16Int64Int32SByteInt16, , UInt32, y ).UInt64 Este tipo difiere de los otros tipos enteros de .NET, que tienen un intervalo indicado por sus MinValue propiedades y MaxValue .

Nota:

Dado que el BigInteger tipo es inmutable (vea Mutability) y porque no tiene límites superiores o inferiores, se puede producir una OutOfMemoryException excepción para cualquier operación que haga que un BigInteger valor crezca demasiado grande.

Creación de una instancia de un objeto BigInteger

Puede crear instancias de un BigInteger objeto de varias maneras:

  • Puede usar la new palabra clave y proporcionar cualquier valor entero o de punto flotante como parámetro para el BigInteger constructor. (Los valores de punto flotante se truncan antes de asignarlos a ). BigInteger En el ejemplo siguiente se muestra cómo usar la new palabra clave para crear instancias BigInteger de valores.

    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
    
  • Puede declarar una BigInteger variable y asignarle un valor igual que lo haría con cualquier tipo numérico, siempre que ese valor sea un tipo entero. En el ejemplo siguiente se usa la asignación para crear un BigInteger valor a partir de .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
    
  • Puede asignar un valor decimal o de punto flotante a un BigInteger objeto si convierte el valor o lo convierte primero. En el ejemplo siguiente se convierten explícitamente (en C#) o se convierte (en Visual Basic) Double y un Decimal valor 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
    

Estos métodos permiten crear instancias de un BigInteger objeto cuyo valor está en el intervalo de uno de los tipos numéricos existentes solo. Puede crear una instancia de un BigInteger objeto cuyo valor puede superar el intervalo de los tipos numéricos existentes de una de estas tres maneras:

  • Puede usar la new palabra clave y proporcionar una matriz de bytes de cualquier tamaño al BigInteger.BigInteger constructor. Por ejemplo:

    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).
    
  • Puede llamar a los Parse métodos o TryParse para convertir la representación de cadena de un número en .BigInteger Por ejemplo:

    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
    
  • Puede llamar a un static método (Shared en Visual Basic) BigInteger que realiza alguna operación en una expresión numérica y devuelve un resultado calculado BigInteger . En el ejemplo siguiente se realiza mediante el cubing UInt64.MaxValue y la asignación del resultado a .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
    

El valor no inicializado de es BigIntegerZero.

Realización de operaciones en valores de BigInteger

Puede usar una BigInteger instancia como usaría cualquier otro tipo entero. BigInteger sobrecarga los operadores numéricos estándar para permitirle realizar operaciones matemáticas básicas, como suma, resta, división, multiplicación y negación unaria. También puede usar los operadores numéricos estándar para comparar dos BigInteger valores entre sí. Al igual que los otros tipos enteros, BigInteger también admite los operadores bit a bit And, Or, XOr, desplazamiento a la izquierda y desplazamiento a la derecha. En el caso de los lenguajes que no admiten operadores personalizados, la BigInteger estructura también proporciona métodos equivalentes para realizar operaciones matemáticas. Entre ellos se incluyen Add, Divide, MultiplyNegate, , Subtracty otros.

Muchos miembros de la BigInteger estructura corresponden directamente a los miembros de los otros tipos enteros. Además, BigInteger agrega miembros como los siguientes:

Muchos de estos miembros adicionales corresponden a los miembros de la Math clase , que proporciona la funcionalidad para trabajar con los tipos numéricos primitivos.

Mutabilidad

En el ejemplo siguiente se crea una instancia de un BigInteger objeto y, a continuación, se incrementa su valor en 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)

Aunque este ejemplo parece modificar el valor del objeto existente, este no es el caso. BigInteger Los objetos son inmutables, lo que significa que, internamente, Common Language Runtime crea realmente un nuevo BigInteger objeto y lo asigna un valor uno mayor que su valor anterior. A continuación, este nuevo objeto se devuelve al autor de la llamada.

Nota:

Los otros tipos numéricos de .NET también son inmutables. Sin embargo, dado que el BigInteger tipo no tiene límites superiores o inferiores, sus valores pueden crecer extremadamente grandes y tener un impacto medible en el rendimiento.

Aunque este proceso es transparente para el autor de la llamada, incurre en una penalización de rendimiento. En algunos casos, especialmente cuando se realizan operaciones repetidas en un bucle en valores muy grandes BigInteger , esa penalización de rendimiento puede ser significativa. Por ejemplo, en el ejemplo siguiente, una operación se realiza repetidamente hasta un millón de veces y un BigInteger valor se incrementa en uno cada vez que la operación se realiza correctamente.

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

En tal caso, puede mejorar el rendimiento realizando todas las asignaciones intermedias a una Int32 variable. A continuación, se puede asignar el BigInteger valor final de la variable al objeto cuando se cierra el bucle. Esto se muestra en el ejemplo siguiente.

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

Matrices de bytes y cadenas hexadecimales

Si convierte BigInteger valores en matrices de bytes o si convierte matrices BigInteger de bytes en valores, debe tener en cuenta el orden de bytes. La BigInteger estructura espera que los bytes individuales de una matriz de bytes aparezcan en orden little-endian (es decir, los bytes de orden inferior del valor preceden a los bytes de orden superior). Puede realizar un recorrido de ida y vuelta de un BigInteger valor llamando al ToByteArray método y pasando la matriz de bytes resultante al BigInteger(Byte[]) constructor, como se muestra en el ejemplo siguiente.

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

Para crear instancias de un BigInteger valor de una matriz de bytes que representa un valor de algún otro tipo entero, puede pasar el valor entero al BitConverter.GetBytes método y, a continuación, pasar la matriz de bytes resultante al BigInteger(Byte[]) constructor. En el ejemplo siguiente se crea una instancia de un BigInteger valor de una matriz de bytes que representa un Int16 valor.

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 estructura supone que los valores negativos se almacenan mediante la representación complementaria de dos. Dado que la BigInteger estructura representa un valor numérico sin longitud fija, el BigInteger(Byte[]) constructor siempre interpreta el bit más significativo del último byte de la matriz como un bit de signo. Para evitar que el BigInteger(Byte[]) constructor confunda la representación complementaria de dos de un valor negativo con la representación de signo y magnitud de un valor positivo, los valores positivos en los que el bit más significativo del último byte de la matriz de bytes normalmente se establecería debería incluir un byte adicional cuyo valor es 0. Por ejemplo, 0xC0 0xBD 0xF0 0xFF es la representación hexadecimal little-endian de -1.000.000 o 4.293.967.296. Dado que el bit más significativo del último byte de esta matriz está activado, el BigInteger(Byte[]) constructor interpretaría el valor de la matriz de bytes como -1000 000. Para crear una instancia de un BigInteger cuyo valor es positivo, se debe pasar a un constructor una matriz de bytes cuyos elementos están 0xC0 0xBD 0xF0 0xFF 0x00. Esto se ilustra en el siguiente ejemplo:

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

Las matrices de bytes creadas por el ToByteArray método a partir de valores positivos incluyen este byte de valor cero adicional. Por lo tanto, la BigInteger estructura puede asignarlos correctamente a valores de ida y vuelta y, a continuación, restaurarlos desde matrices de bytes, como se muestra en el ejemplo siguiente.

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

Sin embargo, es posible que deba agregar este byte de valor cero adicional a matrices de bytes creadas dinámicamente por el desarrollador o que devuelven los métodos que convierten enteros sin signo en matrices de bytes (como BitConverter.GetBytes(UInt16), BitConverter.GetBytes(UInt32)y BitConverter.GetBytes(UInt64)).

Al analizar una cadena hexadecimal, los BigInteger.Parse(String, NumberStyles) métodos y BigInteger.Parse(String, NumberStyles, IFormatProvider) asumen que si se establece el bit más significativo del primer byte de la cadena, o si el primer dígito hexadecimal de la cadena representa los cuatro bits inferiores de un valor de byte, el valor se representa mediante la representación complementaria de dos. Por ejemplo, "FF01" y "F01" representan el valor decimal -255. Para diferenciar los valores positivos de los valores negativos, los valores positivos deben incluir un cero inicial. Las sobrecargas pertinentes del ToString método, cuando se pasan la cadena de formato "X", agregan un cero inicial a la cadena hexadecimal devuelta para los valores positivos. Esto permite realizar un recorrido de ida y vuelta BigInteger mediante los ToString métodos y Parse , como se muestra en el ejemplo siguiente.

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.

Sin embargo, las cadenas hexadecimales creadas llamando a los ToString métodos de los otros tipos enteros o las sobrecargas del ToString método que incluyen un toBase parámetro no indican el signo del valor o el tipo de datos de origen desde el que se derivaba la cadena hexadecimal. La creación correcta de instancias de un BigInteger valor de dicha cadena requiere cierta lógica adicional. En el ejemplo siguiente se proporciona una posible implementación.

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.