BigInteger Construtores
Definição
Importante
Algumas informações dizem respeito a um produto pré-lançado que pode ser substancialmente modificado antes de ser lançado. A Microsoft não faz garantias, de forma expressa ou implícita, em relação à informação aqui apresentada.
Inicializa uma nova instância da BigInteger estrutura.
Sobrecargas
| Name | Description |
|---|---|
| BigInteger(Byte[]) |
Inicializa uma nova instância da BigInteger estrutura usando os valores num array de bytes. |
| BigInteger(Decimal) |
Inicializa uma nova instância da BigInteger estrutura usando um Decimal valor. |
| BigInteger(Double) |
Inicializa uma nova instância da BigInteger estrutura usando um valor de ponto flutuante de dupla precisão. |
| BigInteger(Int32) |
Inicializa uma nova instância da BigInteger estrutura usando um valor inteiro assinado de 32 bits. |
| BigInteger(Int64) |
Inicializa uma nova instância da BigInteger estrutura usando um valor inteiro assinado de 64 bits. |
| BigInteger(Single) |
Inicializa uma nova instância da BigInteger estrutura usando um valor de ponto flutuante de precisão simples. |
| BigInteger(UInt32) |
Inicializa uma nova instância da BigInteger estrutura usando um valor inteiro de 32 bits sem sinal. |
| BigInteger(UInt64) |
Inicializa uma nova instância da BigInteger estrutura com um valor inteiro de 64 bits sem sinal. |
| BigInteger(ReadOnlySpan<Byte>, Boolean, Boolean) |
Inicializa uma nova instância da BigInteger estrutura usando os valores num intervalo de bytes apenas de leitura, indicando opcionalmente a codificação de assinatura e a ordem dos bytes endianness. |
BigInteger(Byte[])
- Origem:
- BigInteger.cs
- Origem:
- BigInteger.cs
- 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 BigInteger estrutura usando os valores num array 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[]
Um array de valores de bytes em ordem little-endian.
- Atributos
Exceções
value é null.
Exemplos
O exemplo seguinte instancia um BigInteger objeto a partir de um array de 5 bytes cujo valor é {5, 4, 3, 2, 1}. Depois, apresenta o BigInteger valor, representado tanto como números decimais como hexadecimais, para a consola. Uma comparação do array de entrada com a saída de texto torna claro porque é que esta sobrecarga do BigInteger construtor de classes cria um BigInteger objeto cujo valor é 4328719365 (ou 0x102030405). O primeiro elemento do array de bytes, cujo valor é 5, define o valor do byte de ordem mais baixa do BigInteger objeto, que é 0x05. O segundo elemento do array de bytes, cujo valor é 4, define o valor do segundo byte do BigInteger objeto, que é 0x04, e assim sucessivamente.
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).
let bytes = [| 5uy; 4uy; 3uy; 2uy; 1uy |]
let number = new BigInteger(bytes)
printfn $"The value of number is {number} (or 0x{number:x})."
// 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 seguinte instancia um valor positivo e um negativo BigInteger , passa-os para o ToByteArray método e depois restaura os valores originais BigInteger do array de bytes resultante. Note que os dois valores são representados por arrays de bytes idênticos. A única diferença entre eles está no bit mais significativo do último elemento do array de bytes. Este bit é definido (o valor do byte é 0xFF) se o array for criado a partir de um valor negativo BigInteger . O bit não está definido (o valor do byte é zero), se o array for criado a partir de 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.
let positiveValue = BigInteger.Parse "4713143110832790377889"
let negativeValue = BigInteger.Add(-Int64.MaxValue, -60000)
// Create two byte arrays.
let positiveBytes = positiveValue.ToByteArray()
let negativeBytes = negativeValue.ToByteArray()
// Instantiate new BigInteger from negativeBytes array.
printf $"Converted {negativeValue:N0} to the byte array "
for byteValue in negativeBytes do
printf $"0x{byteValue:x2} "
printfn ""
let negativeValue2 = bigint negativeBytes
printfn $"Converted the byte array to {negativeValue2:N0}"
printfn ""
// Instantiate new BigInteger from positiveBytes array.
printf $"Converted {positiveValue:N0} to the byte array "
for byteValue in positiveBytes do
printf $"0x{byteValue:x2} "
printfn ""
let positiveValue2 = new BigInteger(positiveBytes)
printfn $"Converted the byte array to {positiveValue2:N0}"
printfn ""
// 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 seguinte ilustra como garantir que um valor positivo não é instanciado incorretamente como valor negativo, adicionando um byte cujo valor é zero ao final do array.
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.
let originalNumber = UInt64.MaxValue
let mutable bytes = BitConverter.GetBytes originalNumber
if originalNumber > 0uL && (bytes[bytes.Length - 1] &&& 0x80uy) > 0uy then
let temp = Array.zeroCreate bytes.Length
Array.Copy(bytes, temp, bytes.Length)
bytes <- Array.zeroCreate (temp.Length + 1)
Array.Copy(temp, bytes, temp.Length)
let newNumber = bigint bytes
printfn $"Converted the UInt64 value {originalNumber:N0} to {newNumber:N0}."
// 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.
Observações
Os bytes individuais no value array devem estar em ordem little-endian, desde o byte de ordem mais baixa até o byte de ordem mais alta. Por exemplo, o valor numérico 1.000.000.000.000.000 é representado conforme mostrado na tabela seguinte:
| Representação | Value |
|---|---|
| Cadeia hexadecimal | E8D4A51000 |
| Array de bytes (primeiro o índice mais baixo) | 00 10 A5 D4 E8 00 |
A maioria dos métodos que convertem valores numéricos em arrays de bytes, como BigInteger.ToByteArray e BitConverter.GetBytes, retornam arrays de bytes em ordem little-endian.
O construtor espera que valores positivos no array de bytes usem representação de signo e magnitude, e valores negativos usem a representação do complemento de dois. Por outras palavras, se o bit de ordem mais alta do byte de ordem mais alta em value estiver definido, o valor resultante BigInteger é negativo. Dependendo da origem do array de bytes, isto pode fazer com que um valor positivo seja interpretado incorretamente como um valor negativo. Os arrays de bytes são normalmente gerados das seguintes formas:
Chamando o método BigInteger.ToByteArray. Como este método devolve um array de bytes com o bit de ordem mais alta do byte de ordem mais alta no array definido para zero para valores positivos, não há hipótese de interpretar um valor positivo como negativo. Arrays de bytes não modificados criados pelo ToByteArray método conseguem sempre fazer uma ida e volta com sucesso quando são passados para o BigInteger(Byte[]) construtor.
Chamando o BitConverter.GetBytes método e passando-lhe um inteiro assinado como parâmetro. Como os inteiros com sinal tratam tanto a representação de sinal e magnitude como a representação do complemento de dois, não há hipótese de interpretar mal um valor positivo como negativo.
Chamando o BitConverter.GetBytes método e passando-lhe um inteiro sem sinal como parâmetro. Como os inteiros sem sinal são representados apenas pela sua magnitude, valores positivos podem ser interpretados erroneamente como valores negativos. Para evitar esta má interpretação, pode adicionar um valor de zero bytes ao final do array. O exemplo na secção seguinte fornece uma ilustração.
Criando um array de bytes, seja dinamicamente ou estaticamente, sem necessariamente chamar nenhum dos métodos anteriores, ou modificando um array de bytes existente. Para evitar que valores positivos sejam interpretados incorretamente como valores negativos, pode adicionar um valor de zero byte ao final do array.
Se value for um array vazio Byte , o novo BigInteger objeto é inicializado para um valor de BigInteger.Zero. Se value for null, o construtor lança um ArgumentNullException.
Ver também
Aplica-se a
BigInteger(Decimal)
- Origem:
- BigInteger.cs
- Origem:
- BigInteger.cs
- Origem:
- BigInteger.cs
- Origem:
- BigInteger.cs
- Origem:
- BigInteger.cs
Inicializa uma nova instância da BigInteger estrutura usando um Decimal valor.
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 seguinte ilustra o uso do BigInteger(Decimal) construtor para instanciar um BigInteger objeto. Define um array de Decimal valores e depois passa cada valor ao BigInteger(Decimal) construtor. Note 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.
let decimalValues = [ -1790.533m; -15.1514m; 18903.79m; 9180098.003m ]
for decimalValue in decimalValues do
let number = bigint decimalValue
printfn $"Instantiated BigInteger value {number} from the Decimal value {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.
Observações
O resultado de chamar este construtor é idêntico a atribuir explicitamente um Decimal valor a uma BigInteger variável.
Chamar este 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
- Origem:
- BigInteger.cs
- Origem:
- BigInteger.cs
Inicializa uma nova instância da BigInteger estrutura usando um valor de ponto flutuante de dupla precisão.
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 dupla precisão.
Exceções
value é NaN, NegativeInfinity, ou PositiveInfinity.
Exemplos
O exemplo seguinte ilustra o uso do BigInteger(Double) construtor para instanciar um BigInteger objeto. Também ilustra a perda de precisão que pode ocorrer quando se utiliza o tipo de Double dado. A Double recebe um valor grande, que depois é atribuído a um BigInteger objeto. Como o resultado mostra, esta tarefa implica uma perda de precisão. Ambos os valores são então incrementados em um. A saída mostra que o BigInteger objeto reflete o valor alterado, enquanto o Double objeto não reflete.
// 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.
let doubleValue = -6e20
let bigIntValue = bigint doubleValue
printfn $"Original Double value: {doubleValue:N0}"
printfn $"Original BigInteger value: {bigIntValue:N0}"
// Increment and then display both values.
let doubleValue = doubleValue + 1.
let bigIntValue = bigIntValue + BigInteger.One
printfn $"Incremented Double value: {doubleValue:N0}"
printfn $"Incremented BigInteger value: {bigIntValue:N0}"
// 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
Observações
Qualquer parte fracionária do value parâmetro é truncada ao instanciar um BigInteger objeto.
Devido à falta de precisão do Double tipo de dado, chamar este construtor pode causar perda de dados.
O BigInteger valor que resulta de chamar este construtor é idêntico ao valor que resulta 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
- Origem:
- BigInteger.cs
- Origem:
- BigInteger.cs
Inicializa uma nova instância da BigInteger estrutura usando um valor inteiro assinado 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 assinado de 32 bits.
Exemplos
O exemplo seguinte chama o BigInteger(Int32) construtor para instanciar BigInteger valores a partir de um array de inteiros de 32 bits. Também utiliza conversão implícita para atribuir a cada valor inteiro de 32 bits a uma BigInteger variável. Depois compara os dois valores para estabelecer que os valores resultantes BigInteger são iguais.
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
let integers = [ Int32.MinValue; -10534; -189; 0; 17; 113439; Int32.MaxValue ]
for number in integers do
let constructed = bigint number
let assigned = number
printfn $"{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
Observações
Não há perda de precisão ao instanciar um BigInteger objeto usando este construtor.
O BigInteger valor que resulta de chamar este 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, SByte, ou UInt16. No entanto, o Int32 tipo suporta a conversão implícita de inteiros e não assinados de 8 e 16 bits em inteiros assinados de 32 bits. Como resultado, este construtor é chamado se value for qualquer um destes quatro tipos de integrais.
Aplica-se a
BigInteger(Int64)
- Origem:
- BigInteger.cs
- Origem:
- BigInteger.cs
- Origem:
- BigInteger.cs
- Origem:
- BigInteger.cs
- Origem:
- BigInteger.cs
Inicializa uma nova instância da BigInteger estrutura usando um valor inteiro assinado 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 assinado de 64 bits.
Exemplos
O exemplo seguinte chama o BigInteger(Int64) construtor para instanciar BigInteger valores a partir de um array de inteiros de 64 bits. Também utiliza conversão implícita para atribuir cada valor inteiro de 64 bits a uma BigInteger variável. Depois compara os dois valores para estabelecer que os valores resultantes BigInteger são iguais.
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:
// -9223372036854775808 = -9223372036854775808: True
// -10534 = -10534: True
// -189 = -189: True
// 0 = 0: True
// 17 = 17: True
// 113439 = 113439: True
// 9223372036854775807 = 9223372036854775807: True
let longs = [ Int64.MinValue; -10534; -189; 0; 17; 113439; Int64.MaxValue ]
for number in longs do
let constructed = bigint number
let assigned = number
printfn $"{constructed} = {assigned}: {constructed.Equals assigned}"
// The example displays the following output:
// -9223372036854775808 = -9223372036854775808: True
// -10534 = -10534: True
// -189 = -189: True
// 0 = 0: True
// 17 = 17: True
// 113439 = 113439: True
// 9223372036854775807 = 9223372036854775807: 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:
' -9223372036854775808 = -9223372036854775808: True
' -10534 = -10534: True
' -189 = -189: True
' 0 = 0: True
' 17 = 17: True
' 113439 = 113439: True
' 9223372036854775807 = 9223372036854775807: True
Observações
Não há perda de precisão ao instanciar um BigInteger objeto usando este construtor.
O BigInteger valor que resulta de chamar este 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
- Origem:
- BigInteger.cs
- Origem:
- BigInteger.cs
Inicializa uma nova instância da BigInteger estrutura 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
value é NaN, NegativeInfinity, ou PositiveInfinity.
Exemplos
O exemplo seguinte ilustra o uso do BigInteger(Single) construtor para instanciar um BigInteger objeto. Também ilustra a perda de precisão que pode ocorrer quando se utiliza o tipo de Single dado. A Single recebe um valor negativo grande, que depois é atribuído a um BigInteger objeto. Como o resultado mostra, esta tarefa implica uma perda de precisão. Ambos os valores são então incrementados em um. A saída mostra que o BigInteger objeto reflete o valor alterado, enquanto o Single objeto não reflete.
// 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
let negativeSingle = Single.MinValue
let negativeNumber = bigint negativeSingle
printfn $"""{negativeSingle.ToString "N0"}"""
printfn $"""{negativeNumber.ToString "N0"}"""
let negativeSingle = negativeSingle + 1f
let negativeNumber = negativeNumber + 1I
printfn $"""{negativeSingle.ToString "N0"}"""
printfn $"""{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
Observações
Qualquer parte fracionária do value parâmetro é truncada ao instanciar um BigInteger objeto.
Devido à falta de precisão do Single tipo de dado, chamar este construtor pode resultar em perda de dados.
O BigInteger valor que resulta de chamar este construtor é idêntico ao valor que resulta 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
- 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 BigInteger estrutura 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 seguinte utiliza o BigInteger(UInt32) construtor e uma instrução de atribuição para inicializar BigInteger valores a partir de um array de inteiros não assinados de 32 bits. Depois 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.
let unsignedValues = [ 0u; 16704u; 199365u; UInt32.MaxValue ]
for unsignedValue in unsignedValues do
let constructedNumber = bigint unsignedValue
let assignedNumber = unsignedValue
if constructedNumber.Equals assignedNumber then
printfn $"Both methods create a BigInteger whose value is {constructedNumber:N0}."
else
printfn $"{constructedNumber:N0} ≠ {assignedNumber:N0}"
// 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.
Observações
Não há perda de precisão ao instanciar a BigInteger usando este construtor.
O BigInteger valor que resulta de chamar este 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
- 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 BigInteger estrutura 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 não assinado de 64 bits.
- Atributos
Exemplos
O exemplo seguinte 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
let unsignedValue = UInt64.MaxValue
let number = bigint unsignedValue
printfn $"{number: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
Observações
Não há perda de precisão ao instanciar a BigInteger usando este construtor.
O BigInteger valor que resulta de chamar este 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
- Origem:
- BigInteger.cs
- Origem:
- BigInteger.cs
Inicializa uma nova instância da BigInteger estrutura usando os valores num intervalo de bytes apenas de leitura, indicando opcionalmente a codificação de assinatura e a ordem dos bytes endianness.
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 apenas de leitura que representa o inteiro grande.
- isUnsigned
- Boolean
true para indicar value usa codificação sem sinal; caso contrário, false (o valor padrão).
- isBigEndian
- Boolean
true para indicar value está em ordem de bytes big-endian; caso contrário, false (o valor padrão).