Observação
O acesso a essa página exige autorização. Você pode tentar entrar ou alterar diretórios.
O acesso a essa página exige autorização. Você pode tentar alterar os diretórios.
Este artigo fornece comentários complementares à documentação de referência para esta API.
O BigInteger tipo é um tipo imutável que representa um inteiro arbitrariamente grande cujo valor em teoria não tem limites superiores ou inferiores. Os membros do tipo BigInteger se assemelham aos dos outros tipos integrais (os tipos Byte, Int16, Int32, Int64, SByte, UInt16, UInt32, e UInt64). Esse tipo difere dos outros tipos integrais no .NET, que têm um intervalo indicado por suas MinValue propriedades e MaxValue propriedades.
Observação
Como o BigInteger tipo é imutável (ver Mutabilidade) e, como ele não tem limites superiores ou inferiores, pode OutOfMemoryException ser gerado para qualquer operação que faça com que um BigInteger valor cresça muito grande.
Instanciar um objeto BigInteger
Você pode criar uma instância de um BigInteger objeto de várias maneiras:
Você pode usar a
newpalavra-chave e fornecer qualquer valor integral ou de ponto flutuante como um parâmetro para o BigInteger construtor. (Os valores de ponto flutuante são truncados antes de serem atribuídos ao BigInteger.) O exemplo a seguir ilustra como usar anewpalavra-chave para instanciar BigInteger 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 // 934157136952Dim 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 ' 934157136952Você pode declarar uma BigInteger variável e atribuir a ela um valor da mesma forma que faria com qualquer tipo numérico, desde que esse valor seja um tipo integral. O exemplo a seguir usa a atribuição para criar um BigInteger valor a partir de um Int64.
long longValue = 6315489358112; BigInteger assignedFromLong = longValue; Console.WriteLine(assignedFromLong); // The example displays the following output: // 6315489358112Dim longValue As Long = 6315489358112 Dim assignedFromLong As BigInteger = longValue Console.WriteLine(assignedFromLong) ' The example displays the following output: ' 6315489358112Você pode atribuir um valor decimal ou de ponto flutuante a um objeto BigInteger se você transformá-lo ou convertê-lo primeiro. O exemplo a seguir converte explicitamente (em C#) ou converte (em Visual Basic) um valor Double e um valor Decimal em um BigInteger.
BigInteger assignedFromDouble = (BigInteger) 179032.6541; Console.WriteLine(assignedFromDouble); BigInteger assignedFromDecimal = (BigInteger) 64312.65m; Console.WriteLine(assignedFromDecimal); // The example displays the following output: // 179032 // 64312Dim 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
Esses métodos permitem criar uma instância de um BigInteger objeto cujo valor está no intervalo de apenas um dos tipos numéricos existentes. Você pode criar uma instância de um BigInteger objeto cujo valor pode exceder o intervalo dos tipos numéricos existentes de uma das três maneiras:
Você pode usar a
newpalavra-chave e fornecer uma matriz de bytes de qualquer tamanho para o BigInteger.BigInteger construtor. Por exemplo: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 {newBigInt} (or 0x{newBigInt:x})."); // 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).Você pode chamar os métodos Parse ou TryParse para converter a representação em cadeia de caracteres de um número em um BigInteger. Por exemplo:
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 '{positiveString}' to a BigInteger value."); } if (BigInteger.TryParse(negativeString, out negBigInt)) Console.WriteLine(negBigInt); else Console.WriteLine($"Unable to convert the string '{negativeString}' to a BigInteger value."); // The example displays the following output: // 9.1389681247993671255432112E+31 // -9.0315837410896312071002088037E+34Dim 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+34Você pode chamar um
staticmétodo (Sharedno Visual Basic) BigInteger que executa alguma operação em uma expressão numérica e retorna um resultado calculado BigInteger . O exemplo a seguir faz isso ao elevar UInt64.MaxValue ao cubo e atribuir o resultado a BigInteger.BigInteger number = BigInteger.Pow(UInt64.MaxValue, 3); Console.WriteLine(number); // The example displays the following output: // 6277101735386680762814942322444851025767571854389858533375Dim number As BigInteger = BigInteger.Pow(UInt64.MaxValue, 3) Console.WriteLine(number) ' The example displays the following output: ' 6277101735386680762814942322444851025767571854389858533375
O valor não inicializado de a BigInteger é Zero.
Executar operações em valores BigInteger
Você pode usar uma BigInteger instância como usaria qualquer outro tipo integral.
BigInteger sobrecarrega os operadores numéricos padrão para permitir que você execute operações matemáticas básicas, como adição, subtração, divisão, multiplicação e negação unária. Você também pode usar os operadores numéricos padrão para comparar dois BigInteger valores entre si. Assim como os outros tipos integrais, BigInteger também dá suporte aos operadores bitwise And, Or, XOr, de deslocamento à esquerda e à direita. Para idiomas que não dão suporte a operadores personalizados, a BigInteger estrutura também fornece métodos equivalentes para executar operações matemáticas. Elas incluem Add, Divide, Multiply, Negate, Subtracte várias outras.
Muitos membros da BigInteger estrutura correspondem diretamente aos membros dos outros tipos integrais. Além disso, BigInteger adiciona membros como o seguinte:
Sign, que retorna um valor que indica o sinal de um valor BigInteger.
Abs, que retorna o valor absoluto de um BigInteger valor.
DivRem, que retorna o quociente e o restante de uma operação de divisão.
GreatestCommonDivisor, que retorna o maior divisor comum de dois BigInteger valores.
Muitos desses membros adicionais correspondem aos membros da classe Math, que fornece a funcionalidade para trabalhar com os tipos numéricos primitivos.
Mutabilidade
O exemplo a seguir cria uma instância do objeto BigInteger e, em seguida, incrementa seu valor em um.
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)
Embora este exemplo pareça modificar o valor do objeto existente, esse não é o caso. BigInteger os objetos são imutáveis, o que significa que, internamente, o common language runtime realmente cria um novo BigInteger objeto e atribui a ele um valor maior que seu valor anterior. Em seguida, esse novo objeto é retornado ao chamador.
Observação
Os outros tipos numéricos no .NET também são imutáveis. No entanto, como o BigInteger tipo não tem limites superiores ou inferiores, seus valores podem crescer muito e ter um impacto mensurável no desempenho.
Embora esse processo seja transparente para o chamador, ele acarreta uma penalidade de performance. Em alguns casos, especialmente quando operações repetidas são executadas em um loop em valores muito grandes BigInteger , essa penalidade de desempenho pode ser significativa. Por exemplo, no exemplo a seguir, uma operação é executada repetidamente até um milhão de vezes e um BigInteger valor é incrementado por um sempre que a operação é bem-sucedida.
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
Nesse caso, você pode melhorar o desempenho executando todas as atribuições intermediárias em uma Int32 variável. O valor final da variável pode ser atribuído ao BigInteger objeto quando o loop é encerrado. O exemplo a seguir ilustra esse cenário.
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
Matrizes de bytes e sequências de caracteres hexadecimais
Se você converter valores BigInteger para matrizes de bytes ou se converter matrizes de bytes para valores BigInteger, deverá considerar a ordem dos bytes. A estrutura BigInteger espera que os bytes individuais em uma matriz de bytes apareçam em ordem little-endian, ou seja, os bytes de ordem inferior do valor precedem os bytes de ordem superior. Você pode fazer uma ida e volta de um valor BigInteger chamando o método ToByteArray e passando a matriz de bytes resultante para o construtor BigInteger(Byte[]), conforme mostra o exemplo a seguir.
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 instanciar um valor de BigInteger a partir de uma matriz de bytes que representa um valor de algum outro tipo integral, você pode passar o valor integral no método BitConverter.GetBytes e, em seguida, passar a matriz de bytes resultante para o construtor BigInteger(Byte[]). O exemplo a seguir instancia um valor BigInteger a partir de uma matriz de bytes que representa um valor Int16.
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
A BigInteger estrutura pressupõe que os valores negativos sejam armazenados usando a representação complementar de dois. Como a BigInteger estrutura representa um valor numérico sem tamanho fixo, o BigInteger(Byte[]) construtor sempre interpreta o bit mais significativo do último byte na matriz como um bit de sinal. Para impedir que o construtor BigInteger(Byte[]) confunda a representação de complemento de dois de um valor negativo com a representação de sinal e magnitude de um valor positivo, os valores positivos nos quais o bit mais significativo do último byte na matriz de bytes normalmente seria configurado devem incluir um byte adicional de valor igual a 0. Por exemplo, 0xC0 0xBD 0xF0 0xFF é a representação hexadecimal no formato little-endian de -1.000.000 ou 4.293.967.296. Como o bit mais significativo do último byte nessa matriz está ativado, o valor da matriz de bytes seria interpretado pelo BigInteger(Byte[]) construtor como -1.000.000. Para instanciar um BigInteger cujo valor é positivo, uma matriz de bytes cujos elementos são 0xC0 0xBD 0xF0 0xFF 0x00 deve ser passada ao construtor. O exemplo a seguir ilustra isso.
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
As matrizes de bytes criadas pelo método a ToByteArray partir de valores positivos incluem esse byte extra de valor zero. Portanto, a BigInteger estrutura pode transferir valores de ida e volta com sucesso ao atribuí-los a matrizes de bytes e restaurá-los, conforme mostrado no exemplo a seguir.
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
No entanto, talvez seja necessário adicionar esse byte de valor zero adicional a matrizes de bytes que são criadas dinamicamente pelo desenvolvedor ou que são retornadas por métodos que convertem inteiros sem sinal em matrizes de bytes (como BitConverter.GetBytes(UInt16), BitConverter.GetBytes(UInt32)e BitConverter.GetBytes(UInt64)).
Ao analisar uma cadeia de caracteres hexadecimal, os métodos BigInteger.Parse(String, NumberStyles) e BigInteger.Parse(String, NumberStyles, IFormatProvider) pressupõem que, se o bit mais significativo do primeiro byte na cadeia de caracteres for definido ou se o primeiro dígito hexadecimal da cadeia de caracteres representar os quatro bits inferiores de um valor de byte, o valor será representado usando a representação complementar de dois. Por exemplo, "FF01" e "F01" representam o valor decimal -255. Para diferenciar valores positivos de valores negativos, os valores positivos devem incluir um número zero à esquerda. As sobrecargas relevantes do método ToString, quando recebem a cadeia de caracteres de formato "X", adicionam um zero à esquerda à cadeia de caracteres hexadecimal retornada para valores positivos. Isso torna possível transportar valores BigInteger de ida e volta usando os métodos ToString e Parse, como mostra o exemplo a seguir.
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 {negativeNumber:N0} to {negativeHex} back to {negativeNumber2:N0}.");
Console.WriteLine($"Converted {positiveNumber:N0} to {positiveHex} back to {positiveNumber2:N0}.");
// 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.
No entanto, as cadeias de caracteres hexadecimais criadas ao chamar os ToString métodos de outros tipos integrais ou as sobrecargas do ToString método que incluem um parâmetro toBase não indicam o sinal do valor nem o tipo de dados de origem do qual foram derivadas. A instanciação com êxito de um BigInteger valor de tal cadeia de caracteres requer alguma lógica adicional. O exemplo a seguir fornece uma implementação possível.
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 {positiveNumber} to {hexValue1.Value} and back to {positiveBigInt}.");
hexString = (hexValue2.Sign == 1 ? "0" : "") + hexValue2.Value;
negativeBigInt = BigInteger.Parse(hexString, NumberStyles.HexNumber);
Console.WriteLine($"Converted {negativeNumber} to {hexValue2.Value} and back to {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.