System.Numerics.BigInteger 구조체

이 문서에서는 이 API에 대한 참조 설명서에 대한 추가 설명서를 제공합니다.

형식은 BigInteger 이론적으로 값에 상한이나 하한이 없는 임의로 큰 정수를 나타내는 변경할 수 없는 형식입니다. 형식의 BigInteger 멤버는 다른 정수 계열 형식(Byte, ,Int16, Int32, Int64, UInt32SByteUInt16및 형식)의 멤버와 UInt64 밀접하게 유사합니다. 이 형식은 .NET의 다른 정수 계열 형식과 다르며, 범위는 해당 MinValue 형식과 MaxValue 속성으로 표시됩니다.

참고 항목

BigInteger 형식은 변경할 수 없고(변경 가능성 참조) 상한이나 하한 OutOfMemoryException 이 없으므로 값이 너무 커지는 BigInteger 모든 작업에 대해 throw될 수 있습니다.

BigInteger 개체 인스턴스화

다음과 같은 여러 가지 방법으로 개체를 BigInteger 인스턴스화할 수 있습니다.

  • 키워드(keyword) 사용하고 new 모든 정수 또는 부동 소수점 값을 생성자에 매개 변수 BigInteger 로 제공할 수 있습니다. (부동 소수점 값은 .에 할당BigInteger되기 전에 잘립니다. 다음 예제에서는 키워드(keyword) 사용하여 new 값을 인스턴스화하는 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
    
  • 변수를 BigInteger 선언하고 해당 값이 정수 형식인 경우 숫자 형식과 마찬가지로 값을 할당할 수 있습니다. 다음 예제에서는 할당을 사용하여 .에서 값을 만듭니 BigIntegerInt64.

    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
    
  • 값을 캐스팅하거나 먼저 변환하는 경우 개체에 BigInteger 소수점 또는 부동 소수점 값을 할당할 수 있습니다. 다음 예제에서는 명시적으로 캐스팅 (C#) 또는 변환 (Visual Basic에서) a DoubleDecimal 값을 합니다 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
    

이러한 메서드를 사용하면 값이 기존 숫자 형식 중 하나의 범위에만 있는 개체를 인스턴스화 BigInteger 할 수 있습니다. 다음 세 가지 방법 중 하나로 값이 기존 숫자 형식의 범위를 초과할 수 있는 개체를 인스턴스화 BigInteger 할 수 있습니다.

  • 키워드(keyword) 사용하고 new 모든 크기의 바이트 배열을 BigInteger.BigInteger 생성자에 제공할 수 있습니다. 예시:

    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).
    
  • 또는 메서드를 Parse 호출하여 숫자의 문자열 표현을 1로 변환할 수 있습니다BigInteger.TryParse 예시:

    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
    
  • 숫자 식에 대해 일부 작업을 수행하고 계산 BigInteger 된 결과를 반환하는 (SharedVisual Basic에서) BigInteger 메서드를 호출 static 할 수 있습니다. 다음 예제에서는 결과를 BigInteger큐핑 UInt64.MaxValue 하고 에 할당하여 이 작업을 수행합니다.

    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
    

초기화되지 않은 값은 . BigInteger 입니다 Zero.

BigInteger 값에 대한 작업 수행

다른 정수 계열 형식을 BigInteger 사용하는 것처럼 인스턴스를 사용할 수 있습니다. BigInteger 표준 숫자 연산자를 오버로드하여 더하기, 빼기, 나누기, 곱하기 및 단항 부정과 같은 기본 수학 연산을 수행할 수 있습니다. 표준 숫자 연산자를 사용하여 두 BigInteger 값을 서로 비교할 수도 있습니다. 다른 정수 계열 형식과 마찬가지로 비트And, BigIntegerOr왼쪽 XOr시프트 및 오른쪽 시프트 연산자도 지원합니다. 사용자 지정 연산자를 지원하지 않는 언어의 BigInteger 경우 이 구조는 수학 연산을 수행하기 위한 동일한 메서드도 제공합니다. 여기에는 , Divide, Multiply, NegateSubtract및 기타 여러 가지가 포함Add됩니다.

구조체의 많은 멤버는 BigInteger 다른 정수 계열 형식의 멤버에 직접 해당합니다. 또한 BigInteger 다음과 같은 멤버를 추가합니다.

이러한 추가 멤버의 대부분은 기본 숫자 형식을 사용할 수 있는 기능을 제공하는 클래스의 Math 멤버에 해당합니다.

가변성

다음 예제에서는 개체를 인스턴스화한 BigInteger 다음 값을 1씩 증분합니다.

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)

이 예제에서는 기존 개체의 값을 수정하는 것처럼 보이지만 그렇지 않습니다. BigInteger 개체는 변경할 수 없습니다. 즉, 내부적으로 공용 언어 런타임은 실제로 새 BigInteger 개체를 만들고 이전 값보다 큰 값을 할당합니다. 그런 다음 이 새 개체가 호출자에게 반환됩니다.

참고 항목

.NET의 다른 숫자 형식도 변경할 수 없습니다. 그러나 형식에 BigInteger 상한 또는 하한이 없으므로 해당 값이 매우 커지고 성능에 측정 가능한 영향을 줄 수 있습니다.

이 프로세스는 호출자에게 투명하지만 성능 저하가 발생합니다. 경우에 따라 특히 매우 큰 BigInteger 값에 대한 루프에서 반복 작업이 수행되는 경우 성능 저하가 클 수 있습니다. 예를 들어 다음 예제에서는 작업이 최대 백만 번 반복적으로 수행되고 BigInteger 작업이 성공할 때마다 값이 하나씩 증가합니다.

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

이러한 경우 변수에 대한 모든 중간 할당을 수행하여 성능을 향상시킬 수 있습니다 Int32 . 그런 다음 루프가 종료될 때 변수의 BigInteger 최종 값을 개체에 할당할 수 있습니다. 다음 예제에서 이에 대해 설명합니다.

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

바이트 배열 및 16진수 문자열

값을 바이트 배열로 변환 BigInteger 하거나 바이트 배열을 값으로 변환하는 BigInteger 경우 바이트 순서를 고려해야 합니다. 이 구조체는 BigInteger 바이트 배열의 개별 바이트가 little-endian 순서로 표시되어야 합니다(즉, 값의 하위 바이트가 상위 바이트보다 우선). 다음 예제와 같이 메서드를 BigInteger 호출 ToByteArray 한 다음 결과 바이트 배열을 생성자에 전달하여 값을 왕복할 BigInteger(Byte[]) 수 있습니다.

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

다른 정수 계열 형식의 값을 나타내는 바이트 배열에서 값을 인스턴스화 BigInteger 하려면 정수 값을 메서드에 BitConverter.GetBytes 전달한 다음 결과 바이트 배열을 BigInteger(Byte[]) 생성자에 전달할 수 있습니다. 다음 예제에서는 값을 나타내는 바이트 배열에서 값을 인스턴스화 BigInteger 합니다 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

구조체는 BigInteger 음수 값이 두 개의 보수 표현을 사용하여 저장된다고 가정합니다. 구조체는 BigInteger 고정 길이 BigInteger(Byte[]) 가 없는 숫자 값을 나타내므로 생성자는 항상 배열의 마지막 바이트 중 가장 중요한 비트를 부호 비트로 해석합니다. 생성자가 음수 값의 두 보완 표현을 양수 값의 부호 및 크기 표현과 혼동하지 않도록 BigInteger(Byte[]) 하려면 바이트 배열에서 마지막 바이트의 가장 중요한 비트가 일반적으로 설정되는 양수 값에는 값이 0인 추가 바이트가 포함되어야 합니다. 예를 들어 0xC0 0xBD 0xF0 0xFF -1,000,000 또는 4,293,967,296의 little-endian 16진수 표현입니다. 이 배열의 마지막 바이트 중 가장 중요한 비트가 켜지므로 바이트 배열의 값은 생성자가 -1,000,000으로 해석 BigInteger(Byte[]) 합니다. 값이 양수인 값을 인스턴스화 BigInteger 하려면 요소가 0xC0 0xBD 0xF0 0xFF 0x00 바이트 배열을 생성자에 전달해야 합니다. 다음 예제에서는 이것을 보여 줍니다.

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

양수 값에서 메서드가 ToByteArray 만든 바이트 배열에는 이 추가 0-값 바이트가 포함됩니다. 따라서 구조체는 BigInteger 다음 예제와 같이 바이트 배열에 할당한 다음 바이트 배열에서 복원하여 성공적으로 왕복 값을 반환할 수 있습니다.

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

그러나 개발자가 동적으로 만들거나 부호 없는 정수를 바이트 배열(예BitConverter.GetBytes(UInt16)BitConverter.GetBytes(UInt32): , 및BitConverter.GetBytes(UInt64))으로 변환하는 메서드에 의해 반환되는 바이트 배열에 이 0 값 바이트를 추가해야 할 수 있습니다.

16진수 문자열 BigInteger.Parse(String, NumberStyles) 을 구문 분석할 때 및 BigInteger.Parse(String, NumberStyles, IFormatProvider) 메서드는 문자열에서 첫 번째 바이트의 가장 중요한 비트가 설정되거나 문자열의 첫 번째 16진수 숫자가 바이트 값의 하위 4비트를 나타내는 경우 값이 2의 보수 표현을 사용하여 표현된다고 가정합니다. 예를 들어 "FF01" 및 "F01"은 모두 10진수 값 -255를 나타냅니다. 음수 값과 긍정을 구분하려면 양수 값에 선행 0이 포함되어야 합니다. 메서드의 ToString 관련 오버로드는 "X" 형식 문자열을 전달할 때 양수 값에 대해 반환된 16진수 문자열에 선행 0을 추가합니다. 이렇게 하면 다음 예제와 같이 메서드와 Parse 메서드를 ToString 사용하여 왕복 BigInteger 값을 사용할 수 있습니다.

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.

그러나 다른 정수 계열 형식의 메서드 또는 매개 변수를 포함하는 toBase 메서드의 ToString 오버로드를 호출 ToString 하여 만든 16진수 문자열은 16진수 문자열이 파생된 값 또는 원본 데이터 형식의 부호를 나타내지 않습니다. 이러한 문자열에서 값을 성공적으로 인스턴스화 BigInteger 하려면 몇 가지 추가 논리가 필요합니다. 다음 예제에서는 하나의 가능한 구현을 제공합니다.

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.