BigInteger.ToByteArray Método

Definição

Sobrecargas

ToByteArray()

Converte um valor de BigInteger em uma matriz de bytes.

ToByteArray(Boolean, Boolean)

Retorna o valor deste BigInteger como uma matriz de bytes usando o menor número possível de bytes. Se o valor é zero, retorna uma matriz de um byte cujo elemento é 0x00.

ToByteArray()

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

Converte um valor de BigInteger em uma matriz de bytes.

public:
 cli::array <System::Byte> ^ ToByteArray();
public byte[] ToByteArray ();
member this.ToByteArray : unit -> byte[]
Public Function ToByteArray () As Byte()

Retornos

Byte[]

O valor do objeto BigInteger atual convertido em uma matriz de bytes.

Exemplos

O exemplo a seguir ilustra como alguns BigInteger valores são representados em matrizes 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
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

Comentários

Os bytes individuais na matriz retornada por esse método aparecem em ordem little-endian. Ou seja, os bytes de ordem inferior do valor precedem os bytes de ordem mais alta. O primeiro byte da matriz reflete os primeiros oito bits do BigInteger valor, o segundo byte reflete os próximos oito bits e assim por diante. Por exemplo, o valor 1024 ou 0x0400 é armazenado como a seguinte matriz de dois bytes:

Elemento Valor do byte
0 0x00
1 0x04

Os valores negativos são gravados na matriz usando a representação complementar de dois na forma mais compacta possível. Por exemplo, -1 é representado como um único byte cujo valor é 0xFF em vez de como uma matriz com vários elementos, como 0xFF, 0xFF ou 0xFF, 0xFF, 0xFF, . 0xFF

Como a representação complementar de dois sempre interpreta o bit de ordem mais alta do último byte na matriz (o byte na posição Array.Length- 1) como o bit de sinal, o método retorna uma matriz de bytes com um elemento extra cujo valor é zero para desambiguar valores positivos que, de outra forma, poderiam ser interpretados como tendo seus bits de sinal definidos. Por exemplo, o valor 120 ou 0x78 é representado como uma matriz de bytes únicos: 0x78. No entanto, 128 ou 0x80, é representado como uma matriz de dois bytes: 0x80, 0x00.

Você pode fazer uma viagem de ida e volta de um BigInteger valor armazenando-o em uma matriz de bytes e restaurando-o usando o BigInteger(Byte[]) construtor .

Cuidado

Se o código modificar o valor de bytes individuais na matriz retornada por esse método antes de restaurar o valor, você deverá garantir que não altere involuntariamente o bit de sinal. Por exemplo, se suas modificações aumentarem um valor positivo para que o bit de ordem mais alta no último elemento da matriz de bytes se torne definido, você poderá adicionar um novo byte cujo valor é zero ao final da matriz.

Aplica-se a

ToByteArray(Boolean, Boolean)

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

Retorna o valor deste BigInteger como uma matriz de bytes usando o menor número possível de bytes. Se o valor é zero, retorna uma matriz 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 a codificação sem sinal; caso contrário, false.

isBigEndian
Boolean

true para gravar os bytes em uma ordem de byte big endian; caso contrário, false.

Retornos

Byte[]

O valor do objeto BigInteger atual convertido em uma matriz de bytes.

Exceções

Se isUnsigned é true, e Sign é negativo.

Comentários

O valor 33022 inteiro pode ser exportado em quatro matrizes diferentes:

Propriedades Resultado
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 }

Aplica-se a