BigInteger.ToByteArray Método
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.
Sobrecargas
| Name | Description |
|---|---|
| ToByteArray() |
Converte um BigInteger valor para um array de bytes. |
| ToByteArray(Boolean, Boolean) |
Devolve o valor disto BigInteger como um array de bytes usando o menor número possível de bytes. Se o valor for zero, devolve um array de um byte cujo elemento é 0x00. |
ToByteArray()
Converte um BigInteger valor para um array de bytes.
public:
cli::array <System::Byte> ^ ToByteArray();
public byte[] ToByteArray();
member this.ToByteArray : unit -> byte[]
Public Function ToByteArray () As Byte()
Devoluções
O valor do objeto atual BigInteger convertido num array de bytes.
Exemplos
O exemplo seguinte ilustra como alguns BigInteger valores são representados em arrays de bytes.
using System;
using System.Numerics;
public class Example
{
static byte[] bytes;
public static void Main()
{
BigInteger[] numbers = { BigInteger.MinusOne, BigInteger.One,
BigInteger.Zero, 120, 128, 255, 1024,
Int64.MinValue, Int64.MaxValue,
BigInteger.Parse("90123123981293054321") };
foreach (BigInteger number in numbers)
{
bytes = number.ToByteArray();
Console.Write("{0} ({1}) -> ", number, number.ToString(GetSpecifier()));
Console.Write("{0} bytes: ", bytes.Length);
foreach (byte byteValue in bytes)
Console.Write("{0:X2} ", byteValue);
Console.WriteLine();
}
}
private static string GetSpecifier()
{
return "X" + (bytes.Length * 2).ToString();
}
}
// The example displays the following output:
// -1 (FF) -> 1 bytes: FF
// 1 (01) -> 1 bytes: 01
// 0 (00) -> 1 bytes: 00
// 120 (78) -> 1 bytes: 78
// 128 (0080) -> 2 bytes: 80 00
// 255 (00FF) -> 2 bytes: FF 00
// 1024 (0400) -> 2 bytes: 00 04
// -9223372036854775808 (8000000000000000) -> 8 bytes: 00 00 00 00 00 00 00 80
// 9223372036854775807 (7FFFFFFFFFFFFFFF) -> 8 bytes: FF FF FF FF FF FF FF 7F
// 90123123981293054321 (04E2B5A7C4A975E971) -> 9 bytes: 71 E9 75 A9 C4 A7 B5 E2 04
open System
open System.Numerics
let numbers =
[| BigInteger.MinusOne
BigInteger.One
BigInteger.Zero
120
128
255
1024
Int64.MinValue
Int64.MaxValue
BigInteger.Parse("90123123981293054321") |]
for number in numbers do
let bytes = number.ToByteArray()
printf $"""{number} ({number.ToString("X" + (bytes.Length * 2).ToString())}) -> """
printf $"{bytes.Length} bytes: "
for byteValue in bytes do
printf $"{byteValue:X2} "
printfn ""
// The example displays the following output:
// -1 (FF) -> 1 bytes: FF
// 1 (01) -> 1 bytes: 01
// 0 (00) -> 1 bytes: 00
// 120 (78) -> 1 bytes: 78
// 128 (0080) -> 2 bytes: 80 00
// 255 (00FF) -> 2 bytes: FF 00
// 1024 (0400) -> 2 bytes: 00 04
// -9223372036854775808 (8000000000000000) -> 8 bytes: 00 00 00 00 00 00 00 80
// 9223372036854775807 (7FFFFFFFFFFFFFFF) -> 8 bytes: FF FF FF FF FF FF FF 7F
// 90123123981293054321 (04E2B5A7C4A975E971) -> 9 bytes: 71 E9 75 A9 C4 A7 B5 E2 04
Imports System.Numerics
Module Example
Dim bytes() As Byte
Public Sub Main()
Dim numbers() As BigInteger = { BigInteger.MinusOne, BigInteger.One,
BigInteger.Zero, 120, 128, 255, 1024,
Int64.MinValue, Int64.MaxValue,
BigInteger.Parse("90123123981293054321") }
For Each number As BigInteger In numbers
bytes = number.ToByteArray()
Console.Write("{0} ({1}) -> ", number, number.ToString(GetSpecifier()))
Console.Write("{0} bytes: ", bytes.Length)
For Each byteValue As Byte In bytes
Console.Write("{0:X2} ", byteValue)
Next
Console.WriteLine()
Next
End Sub
Private Function GetSpecifier() As String
Return "X" + CStr(bytes.Length * 2)
End Function
End Module
' The example displays the following output:
' -1 (FF) -> 1 bytes: FF
' 1 (01) -> 1 bytes: 01
' 0 (00) -> 1 bytes: 00
' 120 (78) -> 1 bytes: 78
' 128 (0080) -> 2 bytes: 80 00
' 255 (00FF) -> 2 bytes: FF 00
' 1024 (0400) -> 2 bytes: 00 04
' -9223372036854775808 (8000000000000000) -> 8 bytes: 00 00 00 00 00 00 00 80
' 9223372036854775807 (7FFFFFFFFFFFFFFF) -> 8 bytes: FF FF FF FF FF FF FF 7F
' 90123123981293054321 (04E2B5A7C4A975E971) -> 9 bytes: 71 E9 75 A9 C4 A7 B5 E2 04
Observações
Os bytes individuais no array devolvido por este método aparecem em ordem little-endian. Ou seja, os bytes de ordem inferior do valor precedem os bytes de ordem superior. O primeiro byte do array reflete os primeiros oito bits do BigInteger valor, o segundo byte reflete os oito bits seguintes, e assim sucessivamente. Por exemplo, o valor 1024, ou 0x0400, é armazenado como o seguinte array de dois bytes:
| Elemento | Valor de byte |
|---|---|
| 0 | 0x00 |
| 1 | 0x04 |
Os valores negativos são escritos no array usando a representação do complemento de dois na forma mais compacta possível. Por exemplo, -1 é representado como um único byte cujo valor é 0xFF em vez de como um array com múltiplos elementos, como 0xFF, 0xFF ou 0xFF, 0xFF, 0xFF, . 0xFF
Como a representação do complemento de dois interpreta sempre o bit de ordem mais alta do último byte do array (o byte na posição Array.Length- 1) como o bit de sinal, o método devolve um array de bytes com um elemento extra cujo valor é zero para desambiguar valores positivos que, de outra forma, poderiam ser interpretados como tendo os seus bits de sinal definidos. Por exemplo, o valor 120 ou 0x78 é representado como um array de um único byte: 0x78. No entanto, 128, ou 0x80, é representado como um array de dois bytes: 0x80, 0x00.
Podes fazer uma ronda de um BigInteger valor armazenando-o num array de bytes e depois restaurá-lo usando o BigInteger(Byte[]) construtor.
Atenção
Se o seu código modificar o valor dos bytes individuais no array devolvido por este método antes de restaurar o valor, deve certificar-se de que não altera involuntariamente o bit de sinal. Por exemplo, se as suas modificações aumentarem um valor positivo de modo que o bit de ordem mais alta no último elemento do array de bytes fique definido, pode adicionar um novo byte cujo valor seja zero ao final do array.
Aplica-se a
ToByteArray(Boolean, Boolean)
Devolve o valor disto BigInteger como um array de bytes usando o menor número possível de bytes. Se o valor for zero, devolve um array de um byte cujo elemento é 0x00.
public byte[] ToByteArray(bool isUnsigned = false, bool isBigEndian = false);
member this.ToByteArray : bool * bool -> byte[]
Public Function ToByteArray (Optional isUnsigned As Boolean = false, Optional isBigEndian As Boolean = false) As Byte()
Parâmetros
- isUnsigned
- Boolean
true para usar codificação sem sinal; caso contrário, false.
- isBigEndian
- Boolean
true para escrever os bytes numa ordem big-endian; caso contrário, false.
Devoluções
O valor do objeto atual BigInteger convertido num array de bytes.
Exceções
Se isUnsigned for true e Sign for negativo.
Observações
O valor 33022 inteiro pode ser exportado em quatro arrays diferentes:
| Properties | Result |
|---|---|
isUnsigned: false, isBigEndian: false |
new byte[] { 0xFE, 0x80, 0x00 } |
isUnsigned: false, isBigEndian: true |
new byte[] { 0x00, 0x80, 0xFE } |
isUnsigned: true, isBigEndian: false |
new byte[] { 0xFE, 0x80 } |
isUnsigned: true, isBigEndian: true |
new byte[] { 0x80, 0xFE } |