BigInteger Конструкторы

Определение

Инициализирует новый экземпляр BigInteger структуры.

Перегрузки

Имя Описание
BigInteger(Byte[])

Инициализирует новый экземпляр BigInteger структуры с помощью значений в массиве байтов.

BigInteger(Decimal)

Инициализирует новый экземпляр BigInteger структуры с помощью Decimal значения.

BigInteger(Double)

Инициализирует новый экземпляр BigInteger структуры с помощью значения с плавающей запятой двойной точности.

BigInteger(Int32)

Инициализирует новый экземпляр структуры с помощью 32-разрядного BigInteger целого числа со знаком.

BigInteger(Int64)

Инициализирует новый экземпляр структуры с помощью 64-разрядного BigInteger целого числа со знаком.

BigInteger(Single)

Инициализирует новый экземпляр BigInteger структуры с помощью значения с плавающей запятой с одной точностью.

BigInteger(UInt32)

Инициализирует новый экземпляр структуры с помощью 32-разрядного BigInteger целого числа без знака.

BigInteger(UInt64)

Инициализирует новый экземпляр BigInteger структуры с 64-разрядным целым числом без знака.

BigInteger(ReadOnlySpan<Byte>, Boolean, Boolean)

Инициализирует новый экземпляр BigInteger структуры с помощью значений в диапазоне только для чтения байтов и при необходимости указывает кодировку подписывания и порядок байтов концевости.

BigInteger(Byte[])

Внимание

Этот API несовместим с CLS.

Инициализирует новый экземпляр BigInteger структуры с помощью значений в массиве байтов.

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())

Параметры

value
Byte[]

Массив байтовых значений в маленьком порядке.

Атрибуты

Исключения

value равно null.

Примеры

В следующем примере создается экземпляр BigInteger объекта из массива байтов 5 элементов, значение которого равно {5, 4, 3, 2, 1}. Затем в консоли отображается BigInteger значение, представленное как десятичным, так и шестнадцатеричным числам. Сравнение входного массива с текстовыми выходными данными дает понять, почему эта перегрузка BigInteger конструктора класса создает BigInteger объект, значение которого 4328719365 (или 0x102030405). Первый элемент массива байтов, значение которого равно 5, определяет значение байта BigInteger наименьшего порядка объекта, которое 0x05. Второй элемент массива байтов, значение которого равно 4, определяет значение второго байта BigInteger объекта, 0x04 и т. д.

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).

В следующем примере создается экземпляр положительного и отрицательного BigInteger значения, передается в ToByteArray метод, а затем восстанавливается исходные BigInteger значения из результирующего массива байтов. Обратите внимание, что эти два значения представлены идентичными массивами байтов. Единственное различие между ними состоит в самом значительном бите последнего элемента в массиве байтов. Этот бит задается (значение байта 0xFF), если массив создается из отрицательного BigInteger значения. Бит не задан (значение байта равно нулю), если массив создается из положительного 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

В следующем примере показано, как убедиться, что положительное значение неправильно создается как отрицательное значение, добавив байт, значение которого равно нулю в конец массива.

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.

Комментарии

Отдельные байты в массиве value должны находиться в малоконечном порядке, от байтов с наименьшим порядком до байтов с наибольшим порядком. Например, числовое значение 1000 000 000 000 000 представлено, как показано в следующей таблице:

Представление Value
Шестнадцатеричная строка E8D4A51000
Массив байтов (самый низкий индекс в первую очередь) 00 10 A5 D4 E8 00

Большинство методов, которые преобразуют числовые значения в массивы байтов, такие как BigInteger.ToByteArray и BitConverter.GetBytes, возвращают массивы байтов в маленьком порядке.

Конструктор ожидает положительных значений в массиве байтов использовать представление знака и величины и отрицательные значения для использования двух дополнительных представлений. Другими словами, если задано значение с наибольшим порядком байта value , результирующее BigInteger значение отрицательно. В зависимости от источника массива байтов это может привести к неправильному интерпретации положительного значения как отрицательного значения. Массивы байтов обычно создаются следующим образом:

  • Вызывая метод BigInteger.ToByteArray. Так как этот метод возвращает массив байтов с битом с наибольшим порядком байта в массиве, равным нулю для положительных значений, вероятность неправильного интерпретации положительного значения как отрицательного. Неизмененные массивы байтов, созданные методом ToByteArray , всегда успешно проходят круговые пути при передаче BigInteger(Byte[]) в конструктор.

  • Вызывая BitConverter.GetBytes метод и передавая в качестве параметра целое число со знаком. Так как целочисленные числа со знаком обрабатывают представление знака и величины, а также дополнительное представление двух, вероятность неправильного толкования положительного значения как отрицательного значения отсутствует.

  • Вызывая BitConverter.GetBytes метод и передавая его целое число без знака в качестве параметра. Поскольку целые числа без знака представлены только их величиной, положительные значения могут быть неправильно интерпретированы как отрицательные значения. Чтобы предотвратить это неправильное представление, можно добавить нулевое байтовое значение в конец массива. Пример в следующем разделе содержит иллюстрацию.

  • Путем создания массива байтов динамически или статически без обязательного вызова любого из предыдущих методов или путем изменения существующего массива байтов. Чтобы предотвратить неправильное понимание положительных значений в качестве отрицательных значений, можно добавить нулевое байтовое значение в конец массива.

Если value это пустой Byte массив, новый BigInteger объект инициализируется в значение BigInteger.Zero. В противном случае valuenullконструктор создает исключение ArgumentNullException.

См. также раздел

Применяется к

BigInteger(Decimal)

Инициализирует новый экземпляр BigInteger структуры с помощью Decimal значения.

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

Параметры

value
Decimal

Десятичное число.

Примеры

В следующем примере показано использование конструктора для создания экземпляра BigInteger(Decimal)BigInteger объекта. Он определяет массив значений Decimal , а затем передает каждое значение конструктору BigInteger(Decimal) . Обратите внимание, что Decimal значение усечено вместо округления при назначении объекту BigInteger .

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.

Комментарии

Результат вызова этого конструктора идентичен явному назначению Decimal значения переменной BigInteger .

Вызов этого конструктора может привести к потере данных; любая дробная часть value усечена при создании экземпляра BigInteger объекта.

Применяется к

BigInteger(Double)

Инициализирует новый экземпляр BigInteger структуры с помощью значения с плавающей запятой двойной точности.

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

Параметры

value
Double

Значение с плавающей точкой двойной точности.

Исключения

Примеры

В следующем примере показано использование конструктора для создания экземпляра BigInteger(Double)BigInteger объекта. Он также демонстрирует потерю точности, которая может возникать при использовании Double типа данных. Назначается Double большое значение, которое затем назначается объекту BigInteger . Как показано в выходных данных, это назначение включает потерю точности. Затем оба значения увеличиваются по одному. Выходные данные показывают, что BigInteger объект отражает измененное значение, а Double объект не является.

// 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

Комментарии

Любая дробная часть value параметра усечена при создании экземпляра BigInteger объекта.

Из-за отсутствия точности Double типа данных вызов этого конструктора может привести к потере данных.

Значение BigInteger , которое приводит к вызову этого конструктора, идентично значению, которое приводит к явному DoubleBigIntegerназначению значения.

Применяется к

BigInteger(Int32)

Инициализирует новый экземпляр структуры с помощью 32-разрядного BigInteger целого числа со знаком.

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

Параметры

value
Int32

32-разрядное целое число со знаком.

Примеры

В следующем примере конструктор вызывает BigInteger(Int32) конструктор для создания экземпляров BigInteger значений из массива 32-разрядных целых чисел. Он также использует неявное преобразование для назначения каждому 32-разрядному целочисленного значения переменной BigInteger . Затем он сравнивает два значения, чтобы установить, что полученные BigInteger значения одинаковы.

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

Комментарии

При создании экземпляра BigInteger объекта с помощью этого конструктора не возникает потери точности.

Значение BigInteger , которое приводит к вызову этого конструктора, идентично значению, которое приводит к назначению Int32 значения значению BigInteger.

Структура BigInteger не включает конструкторы с параметром типа Byte, Int16SByteили UInt16. Однако тип Int32 поддерживает неявное преобразование 8-разрядных и 16-разрядных целых чисел со знаком и без знака в 32-разрядные целые числа. В результате этот конструктор вызывается, если value один из этих четырех целочисленных типов.

Применяется к

BigInteger(Int64)

Инициализирует новый экземпляр структуры с помощью 64-разрядного BigInteger целого числа со знаком.

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

Параметры

value
Int64

64-разрядное целое число со знаком.

Примеры

В следующем примере конструктор вызывает BigInteger(Int64) конструктор для создания экземпляров BigInteger значений из массива 64-разрядных целых чисел. Он также использует неявное преобразование для назначения каждому 64-разрядному целочисленного значения переменной BigInteger . Затем он сравнивает два значения, чтобы установить, что полученные BigInteger значения одинаковы.

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

Комментарии

При создании экземпляра BigInteger объекта с помощью этого конструктора не возникает потери точности.

Значение BigInteger , которое приводит к вызову этого конструктора, идентично значению, которое приводит к назначению Int64 значения значению BigInteger.

Применяется к

BigInteger(Single)

Инициализирует новый экземпляр BigInteger структуры с помощью значения с плавающей запятой с одной точностью.

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

Параметры

value
Single

Значение с плавающей точкой одиночной точности.

Исключения

Примеры

В следующем примере показано использование конструктора для создания экземпляра BigInteger(Single)BigInteger объекта. Он также демонстрирует потерю точности, которая может возникать при использовании Single типа данных. Назначается Single большое отрицательное значение, которое затем назначается объекту BigInteger . Как показано в выходных данных, это назначение включает потерю точности. Затем оба значения увеличиваются по одному. Выходные данные показывают, что BigInteger объект отражает измененное значение, а Single объект не является.

// 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

Комментарии

Любая дробная часть value параметра усечена при создании экземпляра BigInteger объекта.

Из-за отсутствия точности Single типа данных вызов этого конструктора может привести к потере данных.

Значение BigInteger , которое приводит к вызову этого конструктора, идентично значению, которое приводит к явному SingleBigIntegerназначению значения.

Применяется к

BigInteger(UInt32)

Внимание

Этот API несовместим с CLS.

Альтернативный вариант, совместимый с CLS
System.Numerics.BigInteger.BigInteger(Int64)

Инициализирует новый экземпляр структуры с помощью 32-разрядного BigInteger целого числа без знака.

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)

Параметры

value
UInt32

Целое число без знака, равное 32-разрядному значению.

Атрибуты

Примеры

В следующем примере конструктор и оператор назначения используются BigInteger(UInt32) для инициализации BigInteger значений из массива незначенных 32-разрядных целых чисел. Затем он сравнивает два значения, чтобы продемонстрировать, что два метода инициализации BigInteger значения создают идентичные результаты.

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.

Комментарии

При создании экземпляра конструктора BigInteger не возникает потери точности.

Значение BigInteger , которое приводит к вызову этого конструктора, идентично значению, которое приводит к назначению UInt32 значения значению BigInteger.

Применяется к

BigInteger(UInt64)

Внимание

Этот API несовместим с CLS.

Альтернативный вариант, совместимый с CLS
System.Numerics.BigInteger.BigInteger(Double)

Инициализирует новый экземпляр BigInteger структуры с 64-разрядным целым числом без знака.

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)

Параметры

value
UInt64

Целое число без знака, 64-разрядное.

Атрибуты

Примеры

В следующем примере конструктор используется BigInteger(UInt64) для создания экземпляра BigInteger объекта, значение которого равно 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

Комментарии

При создании экземпляра конструктора BigInteger не возникает потери точности.

Значение BigInteger , которое приводит к вызову этого конструктора, идентично значению, которое приводит к назначению UInt64 значения значению BigInteger.

Применяется к

BigInteger(ReadOnlySpan<Byte>, Boolean, Boolean)

Инициализирует новый экземпляр BigInteger структуры с помощью значений в диапазоне только для чтения байтов и при необходимости указывает кодировку подписывания и порядок байтов концевости.

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)

Параметры

value
ReadOnlySpan<Byte>

Диапазон только для чтения байтов, представляющий большое целое число.

isUnsigned
Boolean

trueЗначение , false чтобы указать value использование без знака кодирования; в противном случае (значение по умолчанию).

isBigEndian
Boolean

true value Значение , false указывающее, находится в порядке байтов больших байтов; в противном случае (значение по умолчанию).

Применяется к