Nota
L'accesso a questa pagina richiede l'autorizzazione. È possibile provare ad accedere o modificare le directory.
L'accesso a questa pagina richiede l'autorizzazione. È possibile provare a modificare le directory.
Questo articolo fornisce osservazioni supplementari alla documentazione di riferimento per questa API.
Il tipo BigInteger è un tipo non modificabile che rappresenta un intero arbitrariamente grande il cui valore in teoria non ha limiti superiori o inferiori. I membri del tipo BigInteger sono strettamente paralleli a quelli di altri tipi integrali (i tipi Byte, Int16, Int32, Int64, SByte, UInt16, UInt32e UInt64). Questo tipo differisce dagli altri tipi integrali in .NET, che hanno un intervallo indicato dalle relative proprietà MinValue
e MaxValue
.
Nota
Poiché il tipo BigInteger non è modificabile (vedere Mutabilità) e poiché non dispone di limiti superiori o inferiori, è possibile generare un OutOfMemoryException per qualsiasi operazione che causa un aumento eccessivo di un valore di BigInteger.
Creare un'istanza di un oggetto BigInteger
È possibile creare un'istanza di un oggetto BigInteger in diversi modi:
È possibile usare la parola chiave
new
e specificare qualsiasi valore integrale o a virgola mobile come parametro per il costruttore BigInteger. I valori a virgola mobile sono troncati prima che vengano assegnati a BigInteger. Nell'esempio seguente viene illustrato come usare la parola chiavenew
istanziando valori BigInteger.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 variabile BigInteger 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 valore BigInteger da 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
È possibile assegnare un valore decimale o a virgola mobile a un oggetto BigInteger 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 un valore Double e di un valore Decimal in un 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 oggetto BigInteger il cui valore è compreso nell'intervallo di uno dei tipi numerici esistenti. È possibile creare un'istanza di un oggetto BigInteger il cui valore può superare l'intervallo dei tipi numerici esistenti in uno dei tre modi seguenti:
È possibile usare la parola chiave
new
e fornire una matrice di byte di qualsiasi dimensione al costruttore BigInteger.BigInteger. Per 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 {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).
È possibile chiamare i metodi Parse o TryParse per convertire la rappresentazione di stringa di un numero in un BigInteger. Per 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 '{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+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 metodo
static
(Shared
in Visual Basic) BigInteger che esegue un'operazione su un'espressione numerica e restituisce un risultato BigInteger calcolato. L'esempio seguente esegue questa operazione cubindo UInt64.MaxValue e assegnando il risultato a 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
Il valore non inizializzato di un BigInteger è Zero.
Eseguire operazioni sui valori BigInteger
È possibile usare un'istanza di BigInteger come si userebbe qualsiasi altro tipo integrale.
BigInteger sovraccarica gli 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 valori BigInteger tra loro. Analogamente agli altri tipi integrali, BigInteger supporta anche gli operatori bit per bit And
, Or
, XOr
, spostamento sinistro e spostamento a destra. Per i linguaggi che non supportano operatori personalizzati, la struttura BigInteger fornisce anche metodi equivalenti per l'esecuzione di operazioni matematiche. Sono inclusi Add, Divide, Multiply, Negate, Subtracte molti altri.
Molti membri della struttura BigInteger corrispondono direttamente ai membri degli altri tipi integrali. Inoltre, BigInteger aggiunge membri come i seguenti:
Sign, che restituisce un valore che indica il segno di un valore BigInteger.
Abs, che restituisce il valore assoluto di un valore BigInteger.
DivRem, che restituisce sia il quoziente che il resto di un'operazione di divisione.
GreatestCommonDivisor, che restituisce il divisore comune più grande di due valori di BigInteger.
Molti di questi membri aggiuntivi corrispondono ai membri della classe Math, che fornisce la funzionalità per lavorare con i tipi numerici primitivi.
Modificabilità
Nell'esempio seguente viene creata un'istanza di un oggetto BigInteger 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 oggetti non sono modificabili, ovvero internamente, Common Language Runtime crea effettivamente un nuovo oggetto BigInteger 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 tipo BigInteger non ha limiti superiori o inferiori, i relativi valori possono crescere 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 di BigInteger molto grandi, 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 valore BigInteger 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 variabile Int32. Il valore finale della variabile può quindi essere assegnato all'oggetto BigInteger all'uscita del ciclo. 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 se si converte le matrici di byte in valori BigInteger, è necessario considerare l'ordine dei byte. La struttura BigInteger prevede che i singoli byte in una matrice di byte vengano visualizzati in ordine little-endian, ovvero i byte in ordine inferiore del valore precedono i byte di ordine superiore. È possibile eseguire il round trip di un valore BigInteger chiamando il metodo ToByteArray e quindi passando la matrice di byte risultante al costruttore BigInteger(Byte[]), 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 valore BigInteger da una matrice di byte che rappresenta un valore di un altro tipo integrale, è possibile passare il valore integrale al metodo BitConverter.GetBytes e quindi passare la matrice di byte risultante al costruttore BigInteger(Byte[]). Nell'esempio seguente viene creata un'istanza di un valore BigInteger da una matrice di byte che rappresenta un valore 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
La struttura BigInteger presuppone che i valori negativi vengano archiviati usando la rappresentazione di complemento di due. Poiché la struttura BigInteger rappresenta un valore numerico senza lunghezza fissa, il costruttore BigInteger(Byte[]) interpreta sempre il bit più significativo dell'ultimo byte nella matrice come bit di segno. Per impedire al costruttore BigInteger(Byte[]) di confondere la rappresentazione complementare 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 in formato little-endian di -1.000.000 oppure di 4.293.967.296. Poiché il bit più significativo dell'ultimo byte in questa matrice è attivo, il valore della matrice di byte viene interpretato dal costruttore BigInteger(Byte[]) come -1.000.000. Per creare un'istanza di un BigInteger il cui valore è positivo, è necessario passare al costruttore una matrice di byte i cui elementi sono 0xC0 0xBD 0xF0 0xFF 0x00. Nell'esempio seguente viene illustrato questo.
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 ToByteArray da valori positivi includono questo byte con valore zero aggiuntivo. Pertanto, la struttura BigInteger può eseguire correttamente un round-trip dei valori assegnandoli e quindi ripristinandoli dalle 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 metodi BigInteger.Parse(String, NumberStyles) 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 metodo ToString, quando viene passata loro la stringa di formato "X", aggiungono uno zero iniziale alla stringa esadecimale restituita per i valori positivi. In questo modo è possibile effettuare il round-trip dei valori BigInteger usando i metodi ToString 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 {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.
Tuttavia, le stringhe esadecimali create chiamando i metodi ToString
degli altri tipi integrali o gli overload del metodo ToString che includono un parametro toBase
non indicano il segno del valore o del tipo di dati di origine da cui è stata derivata la stringa esadecimale. Per creare con successo un'istanza di un valore BigInteger da tale stringa, è necessaria una logica essenziale. 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 {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.