BigInteger Construtores

Definição

Inicializa uma nova instância da estrutura BigInteger.

Sobrecargas

BigInteger(Byte[])

Inicializa uma nova instância da estrutura BigInteger usando os valores de uma matriz de bytes.

BigInteger(Decimal)

Inicializa uma nova instância da estrutura BigInteger usando um valor Decimal.

BigInteger(Double)

Inicializa uma nova instância de estrutura BigInteger usando um valor de ponto flutuante de precisão dupla.

BigInteger(Int32)

Inicializa uma nova instância da estrutura BigInteger usando um valor inteiro com sinal de 32 bits.

BigInteger(Int64)

Inicializa uma nova instância da estrutura BigInteger usando um valor inteiro com sinal de 64 bits.

BigInteger(Single)

Inicializa uma nova instância da estrutura BigInteger usando um valor de ponto flutuante de precisão simples.

BigInteger(UInt32)

Inicializa uma nova instância da estrutura BigInteger usando um valor inteiro de 32 bits sem sinal.

BigInteger(UInt64)

Inicializa uma nova instância da estrutura BigInteger com um valor inteiro de 64 bits sem sinal.

BigInteger(ReadOnlySpan<Byte>, Boolean, Boolean)

Inicializa uma nova instância da estrutura BigInteger usando os valores em um intervalo de bytes somente leitura e, opcionalmente, indicando a codificação de assinatura e a ordem de byte com endian.

BigInteger(Byte[])

Origem:
BigInteger.cs
Origem:
BigInteger.cs
Origem:
BigInteger.cs

Importante

Esta API não está em conformidade com CLS.

Inicializa uma nova instância da estrutura BigInteger usando os valores de uma matriz de bytes.

public:
 BigInteger(cli::array <System::Byte> ^ value);
[System.CLSCompliant(false)]
public BigInteger (byte[] value);
[<System.CLSCompliant(false)>]
new System.Numerics.BigInteger : byte[] -> System.Numerics.BigInteger
Public Sub New (value As Byte())

Parâmetros

value
Byte[]

Uma matriz de valores de bytes em ordem little endian.

Atributos

Exceções

value é null.

Exemplos

O exemplo a seguir cria uma instância de um BigInteger objeto de uma matriz de bytes de 5 elementos cujo valor é {5, 4, 3, 2, 1}. Em seguida, ele exibe o BigInteger valor, representado como números decimal e hexadecimal, para o console. Uma comparação da matriz de entrada com a saída de texto deixa claro por que essa sobrecarga do BigInteger construtor de classe cria um BigInteger objeto cujo valor é 4328719365 (ou 0x102030405). O primeiro elemento da matriz de bytes, cujo valor é 5, define o valor do byte de ordem mais baixa do BigInteger objeto, que é 0x05. O segundo elemento da matriz de bytes, cujo valor é 4, define o valor do segundo byte do BigInteger objeto, que é 0x04 e assim por diante.

byte[] bytes = { 5, 4, 3, 2, 1 };
BigInteger number = new BigInteger(bytes);
Console.WriteLine("The value of number is {0} (or 0x{0:x}).", number);
// The example displays the following output:
//    The value of number is 4328719365 (or 0x102030405).
Dim bytes() As Byte = { 5, 4, 3, 2, 1 }
Dim number As New BigInteger(bytes)
Console.WriteLine("The value of number is {0} (or 0x{0:x}).", number) 
' The example displays the following output:
'    The value of number is 4328719365 (or 0x102030405).

O exemplo a seguir cria uma instância de um valor positivo e negativo BigInteger , passa-os para o ToByteArray método e, em seguida, restaura os valores originais BigInteger da matriz de bytes resultante. Observe que os dois valores são representados por matrizes de bytes idênticas. A única diferença entre eles está no bit mais significativo do último elemento na matriz de bytes. Esse bit será definido (o valor do byte será 0xFF) se a matriz for criada com base em um valor negativo BigInteger . O bit não é definido (o valor do byte é zero), se a matriz for criada com base em um valor positivo BigInteger .

// Instantiate BigInteger values.
BigInteger positiveValue = BigInteger.Parse("4713143110832790377889");
BigInteger negativeValue = BigInteger.Add(-Int64.MaxValue, -60000);
BigInteger positiveValue2, negativeValue2;

// Create two byte arrays.
byte[] positiveBytes = positiveValue.ToByteArray();
byte[] negativeBytes = negativeValue.ToByteArray();

// Instantiate new BigInteger from negativeBytes array.
Console.Write("Converted {0:N0} to the byte array ", negativeValue);
foreach (byte byteValue in negativeBytes)
   Console.Write("{0:X2} ", byteValue);
Console.WriteLine();
negativeValue2 = new BigInteger(negativeBytes);
Console.WriteLine("Converted the byte array to {0:N0}", negativeValue2);
Console.WriteLine();

// Instantiate new BigInteger from positiveBytes array.
Console.Write("Converted {0:N0} to the byte array ", positiveValue);
foreach (byte byteValue in positiveBytes)
   Console.Write("{0:X2} ", byteValue);
Console.WriteLine();
positiveValue2 = new BigInteger(positiveBytes);
Console.WriteLine("Converted the byte array to {0:N0}", positiveValue2);
Console.WriteLine();
// The example displays the following output:
//    Converted -9,223,372,036,854,835,807 to the byte array A1 15 FF FF FF FF FF 7F FF
//    Converted the byte array to -9,223,372,036,854,835,807
//
//    Converted 4,713,143,110,832,790,377,889 to the byte array A1 15 FF FF FF FF FF 7F FF 00
//    Converted the byte array to 4,713,143,110,832,790,377,889
' Instantiate BigInteger values.
Dim positiveValue As BigInteger = BigInteger.Parse("4713143110832790377889")
Dim negativeValue As BigInteger = BigInteger.Add(-Int64.MaxValue, -60000) 
Dim positiveValue2, negativeValue2 As BigInteger

' Create two byte arrays.
Dim positiveBytes() As Byte = positiveValue.ToByteArray()
Dim negativeBytes() As Byte = negativeValue.ToByteArray()

' Instantiate new BigInteger from negativeBytes array.
Console.Write("Converted {0:N0} to the byte array ", negativeValue)
For Each byteValue As Byte In negativeBytes
   Console.Write("{0:X2} ", byteValue)
Next 
Console.WriteLine()
negativeValue2 = New BigInteger(negativeBytes)
Console.WriteLine("Converted the byte array to {0:N0}", negativeValue2)
Console.WriteLine()

' Instantiate new BigInteger from positiveBytes array.
Console.Write("Converted {0:N0} to the byte array ", positiveValue)
For Each byteValue As Byte In positiveBytes
   Console.Write("{0:X2} ", byteValue)
Next 
Console.WriteLine()
positiveValue2 = New BigInteger(positiveBytes)
Console.WriteLine("Converted the byte array to {0:N0}", positiveValue2)
Console.WriteLine()
' The example displays the following output:
'    Converted -9,223,372,036,854,835,807 to the byte array A1 15 FF FF FF FF FF 7F FF
'    Converted the byte array to -9,223,372,036,854,835,807
'    
'    Converted 4,713,143,110,832,790,377,889 to the byte array A1 15 FF FF FF FF FF 7F FF 00
'    Converted the byte array to 4,713,143,110,832,790,377,889

O exemplo a seguir ilustra como garantir que um valor positivo não seja instanciado incorretamente como um valor negativo adicionando um byte cujo valor é zero ao final da matriz.

ulong originalNumber = UInt64.MaxValue;
byte[] bytes = BitConverter.GetBytes(originalNumber);
if (originalNumber > 0 && (bytes[bytes.Length - 1] & 0x80) > 0)
{
   byte[] temp = new byte[bytes.Length];
   Array.Copy(bytes, temp, bytes.Length);
   bytes = new byte[temp.Length + 1];
   Array.Copy(temp, bytes, temp.Length);
}

BigInteger newNumber = new BigInteger(bytes);
Console.WriteLine("Converted the UInt64 value {0:N0} to {1:N0}.",
                  originalNumber, newNumber);
// The example displays the following output:
//    Converted the UInt64 value 18,446,744,073,709,551,615 to 18,446,744,073,709,551,615.
Dim originalNumber As ULong = UInt64.MaxValue
' Convert an unsigned integer to a byte array.
Dim bytes() As Byte = BitConverter.GetBytes(originalNumber)
' Determine whether the MSB of the highest-order byte is set.
If originalNumber > 0 And (bytes(bytes.Length - 1) And &h80) > 0 Then
   ' If the MSB is set, add one zero-value byte to the end of the array.
   ReDim Preserve bytes(bytes.Length)
End If

Dim newNumber As New BigInteger(bytes)
Console.WriteLine("Converted the UInt64 value {0:N0} to {1:N0}.", 
                  originalNumber, newNumber) 
' The example displays the following output:
'    Converted the UInt64 value 18,446,744,073,709,551,615 to 18,446,744,073,709,551,615.

Comentários

Os bytes individuais na value matriz devem estar em ordem little-endian, de byte de ordem mais baixa a byte de ordem mais alta. Por exemplo, o valor numérico 1.000.000.000.000 é representado conforme mostrado na tabela a seguir:

Cadeia de caracteres hexadecimal E8D4A51000
Matriz de bytes (índice mais baixo primeiro) 00 10 A5 D4 E8 00

A maioria dos métodos que convertem valores numéricos em matrizes de bytes, como BigInteger.ToByteArray e BitConverter.GetBytes, retornam matrizes de bytes em ordem little-endian.

O construtor espera que valores positivos na matriz de bytes usem representação de sinal e magnitude e valores negativos para usar a representação complementar de dois. Em outras palavras, se o bit de ordem mais alta do byte de ordem mais alta em value for definido, o valor resultante BigInteger será negativo. Dependendo da origem da matriz de bytes, isso pode fazer com que um valor positivo seja interpretado incorretamente como um valor negativo. As matrizes de bytes normalmente são geradas das seguintes maneiras:

  • Chamando o BigInteger.ToByteArray método . Como esse método retorna uma matriz de bytes com o bit de ordem mais alta do byte de ordem mais alta na matriz definida como zero para valores positivos, não há nenhuma chance de interpretar incorretamente um valor positivo como negativo. Matrizes de bytes não modificadas criadas pelo ToByteArray método sempre são realizadas de ida e volta com êxito quando são passadas para o BigInteger(Byte[]) construtor.

  • Chamando o BitConverter.GetBytes método e passando-o um inteiro com sinal como um parâmetro. Como os inteiros com sinal lidam com a representação de sinal e magnitude e a representação complementar de dois, não há nenhuma chance de interpretar incorretamente um valor positivo como negativo.

  • Chamando o BitConverter.GetBytes método e passando-o um inteiro sem sinal como um parâmetro. Como inteiros sem sinal são representados apenas por sua magnitude, valores positivos podem ser interpretados incorretamente como valores negativos. Para evitar essa interpretação incorreta, você pode adicionar um valor de byte zero ao final da matriz. O exemplo na próxima seção fornece uma ilustração.

  • Criando uma matriz de bytes dinamicamente ou estaticamente sem necessariamente chamar nenhum dos métodos anteriores ou modificando uma matriz de bytes existente. Para evitar que valores positivos sejam mal interpretados como valores negativos, você pode adicionar um valor de byte zero ao final da matriz.

Se value for uma matriz vazia Byte , o novo BigInteger objeto será inicializado para um valor de BigInteger.Zero. Se value for null, o construtor lançará um ArgumentNullException.

Confira também

Aplica-se a

BigInteger(Decimal)

Origem:
BigInteger.cs
Origem:
BigInteger.cs
Origem:
BigInteger.cs

Inicializa uma nova instância da estrutura BigInteger usando um valor Decimal.

public:
 BigInteger(System::Decimal value);
public BigInteger (decimal value);
new System.Numerics.BigInteger : decimal -> System.Numerics.BigInteger
Public Sub New (value As Decimal)

Parâmetros

value
Decimal

Um número decimal.

Exemplos

O exemplo a seguir ilustra o uso do BigInteger(Decimal) construtor para instanciar um BigInteger objeto . Ele define uma matriz de Decimal valores e, em seguida, passa cada valor para o BigInteger(Decimal) construtor. Observe que o Decimal valor é truncado em vez de arredondado quando é atribuído ao BigInteger objeto .

decimal[] decimalValues = { -1790.533m, -15.1514m, 18903.79m, 9180098.003m };
foreach (decimal decimalValue in decimalValues)
{
   BigInteger number = new BigInteger(decimalValue);
   Console.WriteLine("Instantiated BigInteger value {0} from the Decimal value {1}.",
                     number, decimalValue);
}
// The example displays the following output:
//    Instantiated BigInteger value -1790 from the Decimal value -1790.533.
//    Instantiated BigInteger value -15 from the Decimal value -15.1514.
//    Instantiated BigInteger value 18903 from the Decimal value 18903.79.
//    Instantiated BigInteger value 9180098 from the Decimal value 9180098.003.
Dim decimalValues() As Decimal = { -1790.533d, -15.1514d, 18903.79d, 9180098.003d }
For Each decimalValue As Decimal In decimalValues
   Dim number As New BigInteger(decimalValue)
   Console.WriteLine("Instantiated BigInteger value {0} from the Decimal value {1}.",
                     number, decimalValue)
Next                 
' The example displays the following output:
'    Instantiated BigInteger value -1790 from the Decimal value -1790.533.
'    Instantiated BigInteger value -15 from the Decimal value -15.1514.
'    Instantiated BigInteger value 18903 from the Decimal value 18903.79.
'    Instantiated BigInteger value 9180098 from the Decimal value 9180098.003.

Comentários

O resultado de chamar esse construtor é idêntico à atribuição explícita de um Decimal valor a uma BigInteger variável.

Chamar esse construtor pode causar perda de dados; qualquer parte fracionária de value é truncada ao instanciar um BigInteger objeto.

Aplica-se a

BigInteger(Double)

Origem:
BigInteger.cs
Origem:
BigInteger.cs
Origem:
BigInteger.cs

Inicializa uma nova instância de estrutura BigInteger usando um valor de ponto flutuante de precisão dupla.

public:
 BigInteger(double value);
public BigInteger (double value);
new System.Numerics.BigInteger : double -> System.Numerics.BigInteger
Public Sub New (value As Double)

Parâmetros

value
Double

Um valor de ponto flutuante de precisão dupla.

Exceções

Exemplos

O exemplo a seguir ilustra o uso do BigInteger(Double) construtor para instanciar um BigInteger objeto . Ele também ilustra a perda de precisão que pode ocorrer quando você usa o Double tipo de dados. Um Double é atribuído a um valor grande, que é atribuído a um BigInteger objeto . Como a saída mostra, essa atribuição envolve uma perda de precisão. Os dois valores são incrementados por um. A saída mostra que o BigInteger objeto reflete o valor alterado, enquanto o Double objeto não.

// Create a BigInteger from a large double value.
double doubleValue = -6e20;
BigInteger bigIntValue = new BigInteger(doubleValue);
Console.WriteLine("Original Double value: {0:N0}", doubleValue);
Console.WriteLine("Original BigInteger value: {0:N0}", bigIntValue);
// Increment and then display both values.
doubleValue++;
bigIntValue += BigInteger.One;
Console.WriteLine("Incremented Double value: {0:N0}", doubleValue);
Console.WriteLine("Incremented BigInteger value: {0:N0}", bigIntValue);
// The example displays the following output:
//    Original Double value: -600,000,000,000,000,000,000
//    Original BigInteger value: -600,000,000,000,000,000,000
//    Incremented Double value: -600,000,000,000,000,000,000
//    Incremented BigInteger value: -599,999,999,999,999,999,999
' Create a BigInteger from a large double value.
Dim doubleValue As Double = -6e20
Dim bigIntValue As New BigInteger(doubleValue)
Console.WriteLine("Original Double value: {0:N0}", doubleValue)
Console.WriteLine("Original BigInteger value: {0:N0}", bigIntValue)
' Increment and then display both values.
doubleValue += 1
bigIntValue += BigInteger.One
Console.WriteLine("Incremented Double value: {0:N0}", doubleValue)
Console.WriteLine("Incremented BigInteger value: {0:N0}", bigIntValue)
' The example displays the following output:
'    Original Double value: -600,000,000,000,000,000,000
'    Original BigInteger value: -600,000,000,000,000,000,000
'    Incremented Double value: -600,000,000,000,000,000,000
'    Incremented BigInteger value: -599,999,999,999,999,999,999

Comentários

Qualquer parte fracionária do value parâmetro é truncada ao instanciar um BigInteger objeto.

Devido à falta de precisão do Double tipo de dados, chamar esse construtor pode causar perda de dados.

O BigInteger valor resultante da chamada desse construtor é idêntico ao valor resultante da atribuição explícita de um Double valor a um BigInteger.

Aplica-se a

BigInteger(Int32)

Origem:
BigInteger.cs
Origem:
BigInteger.cs
Origem:
BigInteger.cs

Inicializa uma nova instância da estrutura BigInteger usando um valor inteiro com sinal de 32 bits.

public:
 BigInteger(int value);
public BigInteger (int value);
new System.Numerics.BigInteger : int -> System.Numerics.BigInteger
Public Sub New (value As Integer)

Parâmetros

value
Int32

Um inteiro com sinal de 32 bits.

Exemplos

O exemplo a seguir chama o BigInteger(Int32) construtor para instanciar BigInteger valores de uma matriz de inteiros de 32 bits. Ele também usa a conversão implícita para atribuir cada valor inteiro de 32 bits a uma BigInteger variável. Em seguida, ele compara os dois valores para estabelecer que os valores resultantes BigInteger são os mesmos.

int[] integers = { Int32.MinValue, -10534, -189, 0, 17, 113439,
                   Int32.MaxValue };
BigInteger constructed, assigned;

foreach (int number in integers)
{
   constructed = new BigInteger(number);
   assigned = number;
   Console.WriteLine("{0} = {1}: {2}", constructed, assigned,
                     constructed.Equals(assigned));
}
// The example displays the following output:
//       -2147483648 = -2147483648: True
//       -10534 = -10534: True
//       -189 = -189: True
//       0 = 0: True
//       17 = 17: True
//       113439 = 113439: True
//       2147483647 = 2147483647: True
Dim integers() As Integer = { Int32.MinValue, -10534, -189, 0, 17, 113439,
                              Int32.MaxValue }
Dim constructed, assigned As BigInteger

For Each number As Integer In integers
   constructed = New BigInteger(number)
   assigned = number
   Console.WriteLine("{0} = {1}: {2}", constructed, assigned, 
                     constructed.Equals(assigned)) 
Next
' The example displays the following output:
'       -2147483648 = -2147483648: True
'       -10534 = -10534: True
'       -189 = -189: True
'       0 = 0: True
'       17 = 17: True
'       113439 = 113439: True
'       2147483647 = 2147483647: True

Comentários

Não há perda de precisão ao instanciar um BigInteger objeto usando esse construtor.

O BigInteger valor resultante da chamada desse construtor é idêntico ao valor que resulta da atribuição de um Int32 valor a um BigInteger.

A BigInteger estrutura não inclui construtores com um parâmetro do tipo Byte, Int16, SByteou UInt16. No entanto, o Int32 tipo dá suporte à conversão implícita de inteiros com sinal de 8 e 16 bits e sem sinal em inteiros assinados de 32 bits. Como resultado, esse construtor é chamado se value for um desses quatro tipos integrais.

Aplica-se a

BigInteger(Int64)

Origem:
BigInteger.cs
Origem:
BigInteger.cs
Origem:
BigInteger.cs

Inicializa uma nova instância da estrutura BigInteger usando um valor inteiro com sinal de 64 bits.

public:
 BigInteger(long value);
public BigInteger (long value);
new System.Numerics.BigInteger : int64 -> System.Numerics.BigInteger
Public Sub New (value As Long)

Parâmetros

value
Int64

Um inteiro com sinal de 64 bits.

Exemplos

O exemplo a seguir chama o BigInteger(Int64) construtor para instanciar BigInteger valores de uma matriz de inteiros de 64 bits. Ele também usa a conversão implícita para atribuir cada valor inteiro de 64 bits a uma BigInteger variável. Em seguida, ele compara os dois valores para estabelecer que os valores resultantes BigInteger são os mesmos.

long[] longs = { Int64.MinValue, -10534, -189, 0, 17, 113439,
                 Int64.MaxValue };
BigInteger constructed, assigned;

foreach (long number in longs)
{
   constructed = new BigInteger(number);
   assigned = number;
   Console.WriteLine("{0} = {1}: {2}", constructed, assigned,
                     constructed.Equals(assigned));
}
// The example displays the following output:
//       -2147483648 = -2147483648: True
//       -10534 = -10534: True
//       -189 = -189: True
//       0 = 0: True
//       17 = 17: True
//       113439 = 113439: True
//       2147483647 = 2147483647: True
Dim longs() As Long = { Int64.MinValue, -10534, -189, 0, 17, 113439,
                              Int64.MaxValue }
Dim constructed, assigned As BigInteger

For Each number As Long In longs
   constructed = New BigInteger(number)
   assigned = number
   Console.WriteLine("{0} = {1}: {2}", constructed, assigned, 
                     constructed.Equals(assigned)) 
Next
' The example displays the following output:
'       -2147483648 = -2147483648: True
'       -10534 = -10534: True
'       -189 = -189: True
'       0 = 0: True
'       17 = 17: True
'       113439 = 113439: True
'       2147483647 = 2147483647: True

Comentários

Não há perda de precisão ao instanciar um BigInteger objeto usando esse construtor.

O BigInteger valor resultante da chamada desse construtor é idêntico ao valor que resulta da atribuição de um Int64 valor a um BigInteger.

Aplica-se a

BigInteger(Single)

Origem:
BigInteger.cs
Origem:
BigInteger.cs
Origem:
BigInteger.cs

Inicializa uma nova instância da estrutura BigInteger usando um valor de ponto flutuante de precisão simples.

public:
 BigInteger(float value);
public BigInteger (float value);
new System.Numerics.BigInteger : single -> System.Numerics.BigInteger
Public Sub New (value As Single)

Parâmetros

value
Single

Um valor de ponto flutuante de precisão simples.

Exceções

Exemplos

O exemplo a seguir ilustra o uso do BigInteger(Single) construtor para instanciar um BigInteger objeto . Ele também ilustra a perda de precisão que pode ocorrer quando você usa o Single tipo de dados. Um Single recebe um valor negativo grande, que é atribuído a um BigInteger objeto . Como a saída mostra, essa atribuição envolve uma perda de precisão. Os dois valores são incrementados por um. A saída mostra que o BigInteger objeto reflete o valor alterado, enquanto o Single objeto não.

// Create a BigInteger from a large negative Single value
float negativeSingle = Single.MinValue;
BigInteger negativeNumber = new BigInteger(negativeSingle);

Console.WriteLine(negativeSingle.ToString("N0"));
Console.WriteLine(negativeNumber.ToString("N0"));

negativeSingle++;
negativeNumber++;

Console.WriteLine(negativeSingle.ToString("N0"));
Console.WriteLine(negativeNumber.ToString("N0"));
// The example displays the following output:
//       -340,282,300,000,000,000,000,000,000,000,000,000,000
//       -340,282,346,638,528,859,811,704,183,484,516,925,440
//       -340,282,300,000,000,000,000,000,000,000,000,000,000
//       -340,282,346,638,528,859,811,704,183,484,516,925,439
' Create a BigInteger from a large negative Single value
Dim negativeSingle As Single = Single.MinValue
Dim negativeNumber As New BigInteger(negativeSingle)

Console.WriteLine(negativeSingle.ToString("N0"))
Console.WriteLine(negativeNumber.ToString("N0"))

negativeSingle += 1
negativeNumber += 1
Console.WriteLine(negativeSingle.ToString("N0"))
Console.WriteLine(negativeNumber.ToString("N0"))
' The example displays the following output:
'       -340,282,300,000,000,000,000,000,000,000,000,000,000
'       -340,282,346,638,528,859,811,704,183,484,516,925,440
'       -340,282,300,000,000,000,000,000,000,000,000,000,000
'       -340,282,346,638,528,859,811,704,183,484,516,925,439

Comentários

Qualquer parte fracionária do value parâmetro é truncada ao instanciar um BigInteger objeto.

Devido à falta de precisão do Single tipo de dados, chamar esse construtor pode resultar em perda de dados.

O BigInteger valor resultante da chamada desse construtor é idêntico ao valor resultante da atribuição explícita de um Single valor a um BigInteger.

Aplica-se a

BigInteger(UInt32)

Origem:
BigInteger.cs
Origem:
BigInteger.cs
Origem:
BigInteger.cs

Importante

Esta API não está em conformidade com CLS.

Alternativa em conformidade com CLS
System.Numerics.BigInteger.BigInteger(Int64)

Inicializa uma nova instância da estrutura BigInteger usando um valor inteiro de 32 bits sem sinal.

public:
 BigInteger(System::UInt32 value);
[System.CLSCompliant(false)]
public BigInteger (uint value);
[<System.CLSCompliant(false)>]
new System.Numerics.BigInteger : uint32 -> System.Numerics.BigInteger
Public Sub New (value As UInteger)

Parâmetros

value
UInt32

Um valor inteiro de 32 bits sem sinal.

Atributos

Exemplos

O exemplo a seguir usa o BigInteger(UInt32) construtor e uma instrução de atribuição para inicializar BigInteger valores de uma matriz de inteiros de 32 bits sem sinal. Em seguida, ele compara os dois valores para demonstrar que os dois métodos de inicialização de um BigInteger valor produzem resultados idênticos.

uint[] unsignedValues = { 0, 16704, 199365, UInt32.MaxValue };
foreach (uint unsignedValue in unsignedValues)
{
   BigInteger constructedNumber = new BigInteger(unsignedValue);
   BigInteger assignedNumber = unsignedValue;
   if (constructedNumber.Equals(assignedNumber))
      Console.WriteLine("Both methods create a BigInteger whose value is {0:N0}.",
                        constructedNumber);
   else
      Console.WriteLine("{0:N0} ≠ {1:N0}", constructedNumber, assignedNumber);
}
// The example displays the following output:
//    Both methods create a BigInteger whose value is 0.
//    Both methods create a BigInteger whose value is 16,704.
//    Both methods create a BigInteger whose value is 199,365.
//    Both methods create a BigInteger whose value is 4,294,967,295.
Dim unsignedValues() As UInteger = { 0, 16704, 199365, UInt32.MaxValue }
For Each unsignedValue As UInteger In unsignedValues
   Dim constructedNumber As New BigInteger(unsignedValue)
   Dim assignedNumber As BigInteger = unsignedValue
   If constructedNumber.Equals(assignedNumber) Then
      Console.WriteLine("Both methods create a BigInteger whose value is {0:N0}.",
                        constructedNumber)
   Else
      Console.WriteLine("{0:N0} ≠ {1:N0}", constructedNumber, assignedNumber)
   End If                         
Next
' The example displays the following output:
'    Both methods create a BigInteger whose value is 0.
'    Both methods create a BigInteger whose value is 16,704.
'    Both methods create a BigInteger whose value is 199,365.
'    Both methods create a BigInteger whose value is 4,294,967,295.

Comentários

Não há perda de precisão ao instanciar um BigInteger usando esse construtor.

O BigInteger valor resultante da chamada desse construtor é idêntico ao valor que resulta da atribuição de um UInt32 valor a um BigInteger.

Aplica-se a

BigInteger(UInt64)

Origem:
BigInteger.cs
Origem:
BigInteger.cs
Origem:
BigInteger.cs

Importante

Esta API não está em conformidade com CLS.

Alternativa em conformidade com CLS
System.Numerics.BigInteger.BigInteger(Double)

Inicializa uma nova instância da estrutura BigInteger com um valor inteiro de 64 bits sem sinal.

public:
 BigInteger(System::UInt64 value);
[System.CLSCompliant(false)]
public BigInteger (ulong value);
[<System.CLSCompliant(false)>]
new System.Numerics.BigInteger : uint64 -> System.Numerics.BigInteger
Public Sub New (value As ULong)

Parâmetros

value
UInt64

Um inteiro de 64 bits sem sinal.

Atributos

Exemplos

O exemplo a seguir usa o BigInteger(UInt64) construtor para instanciar um BigInteger objeto cujo valor é igual a MaxValue.

ulong unsignedValue = UInt64.MaxValue;
BigInteger number = new BigInteger(unsignedValue);
Console.WriteLine(number.ToString("N0"));
// The example displays the following output:
//       18,446,744,073,709,551,615
Dim unsignedValue As ULong = UInt64.MaxValue
Dim number As New BigInteger(unsignedValue)
Console.WriteLine(number.ToString("N0"))       
' The example displays the following output:
'       18,446,744,073,709,551,615

Comentários

Não há perda de precisão ao instanciar um BigInteger usando esse construtor.

O BigInteger valor resultante da chamada desse construtor é idêntico ao valor que resulta da atribuição de um UInt64 valor a um BigInteger.

Aplica-se a

BigInteger(ReadOnlySpan<Byte>, Boolean, Boolean)

Origem:
BigInteger.cs
Origem:
BigInteger.cs
Origem:
BigInteger.cs

Inicializa uma nova instância da estrutura BigInteger usando os valores em um intervalo de bytes somente leitura e, opcionalmente, indicando a codificação de assinatura e a ordem de byte com endian.

public BigInteger (ReadOnlySpan<byte> value, bool isUnsigned = false, bool isBigEndian = false);
new System.Numerics.BigInteger : ReadOnlySpan<byte> * bool * bool -> System.Numerics.BigInteger
Public Sub New (value As ReadOnlySpan(Of Byte), Optional isUnsigned As Boolean = false, Optional isBigEndian As Boolean = false)

Parâmetros

value
ReadOnlySpan<Byte>

Um intervalo de bytes somente leitura que representa o inteiro grande.

isUnsigned
Boolean

true para indicar que value usa codificação sem sinal; caso contrário, false (o valor padrão).

isBigEndian
Boolean

true para indicar value que está em ordem de bytes big-endian; caso contrário, false (o valor padrão).

Aplica-se a