BigInteger.ToByteArray Método
Definición
Importante
Parte de la información hace referencia a la versión preliminar del producto, que puede haberse modificado sustancialmente antes de lanzar la versión definitiva. Microsoft no otorga ninguna garantía, explícita o implícita, con respecto a la información proporcionada aquí.
Sobrecargas
| Nombre | Description |
|---|---|
| ToByteArray() |
Convierte un BigInteger valor en una matriz de bytes. |
| ToByteArray(Boolean, Boolean) |
Devuelve el valor de esto BigInteger como una matriz de bytes con el menor número de bytes posible. Si el valor es cero, devuelve una matriz de un byte cuyo elemento es 0x00. |
ToByteArray()
Convierte un BigInteger valor en una matriz de bytes.
public:
cli::array <System::Byte> ^ ToByteArray();
public byte[] ToByteArray();
member this.ToByteArray : unit -> byte[]
Public Function ToByteArray () As Byte()
Devoluciones
Valor del objeto actual BigInteger convertido en una matriz de bytes.
Ejemplos
En el ejemplo siguiente se muestra cómo se representan algunos BigInteger valores en matrices 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
Comentarios
Los bytes individuales de la matriz devueltas por este método aparecen en orden little-endian. Es decir, los bytes de orden inferior del valor preceden a los bytes de orden superior. El primer byte de la matriz refleja los ocho primeros bits del BigInteger valor, el segundo byte refleja los ocho bits siguientes, etc. Por ejemplo, el valor 1024 o 0x0400, se almacena como la matriz siguiente de dos bytes:
| Elemento | Valor byte |
|---|---|
| 0 | 0x00 |
| 1 | 0x04 |
Los valores negativos se escriben en la matriz mediante la representación complementaria de dos en la forma más compacta posible. Por ejemplo, -1 se representa como un solo byte cuyo valor es 0xFF en lugar de como una matriz con varios elementos, como 0xFF, 0xFF o 0xFF, 0xFF, , 0xFF. 0xFF
Dado que la representación complementaria de dos siempre interpreta el bit de orden más alto del último byte de la matriz (el byte en la posición Array.Length- 1) como bit de signo, el método devuelve una matriz de bytes con un elemento adicional cuyo valor es cero para desambiguar los valores positivos que, de lo contrario, se podrían interpretar como tener sus bits de signo establecidos. Por ejemplo, el valor 120 o 0x78 se representa como una matriz de un solo byte: 0x78. Sin embargo, 128 o 0x80, se representa como una matriz de dos bytes: 0x80, 0x00.
Para realizar un recorrido de ida y vuelta, puede BigInteger almacenarlo en una matriz de bytes y, a continuación, restaurarlo mediante el BigInteger(Byte[]) constructor .
Caution
Si el código modifica el valor de bytes individuales en la matriz devuelta por este método antes de restaurar el valor, debe asegurarse de que no cambie involuntariamente el bit de signo. Por ejemplo, si las modificaciones aumentan un valor positivo para que el bit de orden más alto del último elemento de la matriz de bytes se establezca, puede agregar un nuevo byte cuyo valor sea cero al final de la matriz.
Se aplica a
ToByteArray(Boolean, Boolean)
Devuelve el valor de esto BigInteger como una matriz de bytes con el menor número de bytes posible. Si el valor es cero, devuelve una matriz de un byte cuyo elemento es 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 la codificación sin signo; de lo contrario, false.
- isBigEndian
- Boolean
true para escribir los bytes en un orden de bytes big-endian; de lo contrario, false.
Devoluciones
Valor del objeto actual BigInteger convertido en una matriz de bytes.
Excepciones
Si isUnsigned es y Sign es true negativo.
Comentarios
El valor 33022 entero se puede exportar en cuatro matrices diferentes:
| Properties | 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 } |