Struct System.Byte

Cet article vous offre des remarques complémentaires à la documentation de référence pour cette API.

Byte est un type valeur immuable qui représente des entiers non signés avec des valeurs comprises entre 0 (qui est représentée par la Byte.MinValue constante) à 255 (qui est représentée par la Byte.MaxValue constante). .NET inclut également un type de valeur entière 8 bits signé, SBytequi représente des valeurs comprises entre -128 et 127.

Instancier une valeur d’octet

Vous pouvez instancier une Byte valeur de plusieurs façons :

  • Vous pouvez déclarer une Byte variable et l’affecter à une valeur entière littérale qui se trouve dans la plage du Byte type de données. L’exemple suivant déclare deux Byte variables et leur attribue des valeurs de cette façon.

    byte value1 = 64;
    byte value2 = 255;
    
    let value1 = 64uy
    let value2 = 255uy
    
    Dim value1 As Byte = 64
    Dim value2 As Byte = 255
    
  • Vous pouvez affecter une valeur numérique non octet à un octet. Il s’agit d’une conversion étroite, ce qui nécessite un opérateur de cast en C# et F#, ou une méthode de conversion en Visual Basic si Option Strict elle est activée. Si la valeur non-octet est un Single, Doubleou Decimal une valeur qui inclut un composant fractionnaire, la gestion de sa partie fractionnaire dépend du compilateur effectuant la conversion. L’exemple suivant affecte plusieurs valeurs numériques à des Byte variables.

    int int1 = 128;
    try
    {
        byte value1 = (byte)int1;
        Console.WriteLine(value1);
    }
    catch (OverflowException)
    {
        Console.WriteLine("{0} is out of range of a byte.", int1);
    }
    
    double dbl2 = 3.997;
    try
    {
        byte value2 = (byte)dbl2;
        Console.WriteLine(value2);
    }
    catch (OverflowException)
    {
        Console.WriteLine("{0} is out of range of a byte.", dbl2);
    }
    // The example displays the following output:
    //       128
    //       3
    
    let int1 = 128
    try
        let value1 = byte int1
        printfn $"{value1}"
    with :? OverflowException ->
        printfn $"{int1} is out of range of a byte."
    
    let dbl2 = 3.997
    try
        let value2 = byte dbl2
        printfn $"{value2}"
    with :? OverflowException ->
        printfn $"{dbl2} is out of range of a byte."
    
    // The example displays the following output:
    //       128
    //       3
    
    Dim int1 As Integer = 128
    Try
        Dim value1 As Byte = CByte(int1)
        Console.WriteLine(value1)
    Catch e As OverflowException
        Console.WriteLine("{0} is out of range of a byte.", int1)
    End Try
    
    Dim dbl2 As Double = 3.997
    Try
        Dim value2 As Byte = CByte(dbl2)
        Console.WriteLine(value2)
    Catch e As OverflowException
        Console.WriteLine("{0} is out of range of a byte.", dbl2)
    End Try
    ' The example displays the following output:
    '       128
    '       4
    
  • Vous pouvez appeler une méthode de la Convert classe pour convertir n’importe quel type pris en charge en valeur Byte . Cela est possible, car Byte prend en charge l’interface IConvertible . L’exemple suivant illustre la conversion d’un tableau de Int32 valeurs en Byte valeurs.

    int[] numbers = { Int32.MinValue, -1, 0, 121, 340, Int32.MaxValue };
    byte result;
    foreach (int number in numbers)
    {
        try
        {
            result = Convert.ToByte(number);
            Console.WriteLine("Converted the {0} value {1} to the {2} value {3}.",
                              number.GetType().Name, number,
                              result.GetType().Name, result);
        }
        catch (OverflowException)
        {
            Console.WriteLine("The {0} value {1} is outside the range of the Byte type.",
                              number.GetType().Name, number);
        }
    }
    // The example displays the following output:
    //       The Int32 value -2147483648 is outside the range of the Byte type.
    //       The Int32 value -1 is outside the range of the Byte type.
    //       Converted the Int32 value 0 to the Byte value 0.
    //       Converted the Int32 value 121 to the Byte value 121.
    //       The Int32 value 340 is outside the range of the Byte type.
    //       The Int32 value 2147483647 is outside the range of the Byte type.
    
    let numbers = [| Int32.MinValue; -1; 0; 121; 340; Int32.MaxValue |]
    for number in numbers do
        try
            let result = Convert.ToByte number
            printfn $"Converted the {number.GetType().Name} value {number} to the {result.GetType().Name} value {result}."
        with :? OverflowException ->
            printfn $"The {number.GetType().Name} value {number} is outside the range of the Byte type."
    // The example displays the following output:
    //       The Int32 value -2147483648 is outside the range of the Byte type.
    //       The Int32 value -1 is outside the range of the Byte type.
    //       Converted the Int32 value 0 to the Byte value 0.
    //       Converted the Int32 value 121 to the Byte value 121.
    //       The Int32 value 340 is outside the range of the Byte type.
    //       The Int32 value 2147483647 is outside the range of the Byte type.
    
    Dim numbers() As Integer = {Int32.MinValue, -1, 0, 121, 340, Int32.MaxValue}
    Dim result As Byte
    For Each number As Integer In numbers
        Try
            result = Convert.ToByte(number)
            Console.WriteLine("Converted the {0} value {1} to the {2} value {3}.",
                          number.GetType().Name, number,
                          result.GetType().Name, result)
        Catch e As OverflowException
            Console.WriteLine("The {0} value {1} is outside the range of the Byte type.",
                          number.GetType().Name, number)
        End Try
    Next
    ' The example displays the following output:
    '       The Int32 value -2147483648 is outside the range of the Byte type.
    '       The Int32 value -1 is outside the range of the Byte type.
    '       Converted the Int32 value 0 to the Byte value 0.
    '       Converted the Int32 value 121 to the Byte value 121.
    '       The Int32 value 340 is outside the range of the Byte type.
    '       The Int32 value 2147483647 is outside the range of the Byte type.
    
  • Vous pouvez appeler la ou TryParse la Parse méthode pour convertir la représentation sous forme de chaîne d’une Byte valeur en Byte. La chaîne peut contenir des chiffres décimaux ou hexadécimaux. L’exemple suivant illustre l’opération d’analyse à l’aide d’une chaîne décimale et hexadécimale.

    string string1 = "244";
    try
    {
        byte byte1 = Byte.Parse(string1);
        Console.WriteLine(byte1);
    }
    catch (OverflowException)
    {
        Console.WriteLine("'{0}' is out of range of a byte.", string1);
    }
    catch (FormatException)
    {
        Console.WriteLine("'{0}' is out of range of a byte.", string1);
    }
    
    string string2 = "F9";
    try
    {
        byte byte2 = Byte.Parse(string2,
                                System.Globalization.NumberStyles.HexNumber);
        Console.WriteLine(byte2);
    }
    catch (OverflowException)
    {
        Console.WriteLine("'{0}' is out of range of a byte.", string2);
    }
    catch (FormatException)
    {
        Console.WriteLine("'{0}' is out of range of a byte.", string2);
    }
    // The example displays the following output:
    //       244
    //       249
    
    let string1 = "244"
    try
        let byte1 = Byte.Parse string1
        printfn $"{byte1}" 
    with
    | :? OverflowException ->
        printfn $"'{string1}' is out of range of a byte."
    | :? FormatException ->
        printfn $"'{string1}' is out of range of a byte."
    
    let string2 = "F9"
    try
        let byte2 = Byte.Parse(string2, System.Globalization.NumberStyles.HexNumber)
        printfn $"{byte2}"
    with
    | :? OverflowException ->
        printfn $"'{string2}' is out of range of a byte."
    | :? FormatException ->
        printfn $"'{string2}' is out of range of a byte."
    
    // The example displays the following output:
    //       244
    //       249
    
    Dim string1 As String = "244"
    Try
        Dim byte1 As Byte = Byte.Parse(string1)
        Console.WriteLine(byte1)
    Catch e As OverflowException
        Console.WriteLine("'{0}' is out of range of a byte.", string1)
    Catch e As FormatException
        Console.WriteLine("'{0}' is out of range of a byte.", string1)
    End Try
    
    Dim string2 As String = "F9"
    Try
        Dim byte2 As Byte = Byte.Parse(string2,
                               System.Globalization.NumberStyles.HexNumber)
        Console.WriteLine(byte2)
    Catch e As OverflowException
        Console.WriteLine("'{0}' is out of range of a byte.", string2)
    Catch e As FormatException
        Console.WriteLine("'{0}' is out of range of a byte.", string2)
    End Try
    ' The example displays the following output:
    '       244
    '       249
    

Effectuer des opérations sur les valeurs d’octet

Le Byte type prend en charge les opérations mathématiques standard telles que l’addition, la soustraction, la division, la multiplication, la soustraction, la négation et la négation unaire. Comme les autres types intégraux, le Byte type prend également en charge les opérateurs bitwise AND, OR, XORleft shift et right shift.

Vous pouvez utiliser les opérateurs numériques standard pour comparer deux Byte valeurs, ou vous pouvez appeler la méthode ou Equals l’utiliserCompareTo.

Vous pouvez également appeler les membres de la Math classe pour effectuer un large éventail d’opérations numériques, notamment obtenir la valeur absolue d’un nombre, calculer le quotient et le reste à partir de la division intégrale, déterminer la valeur maximale ou minimale de deux entiers, obtenir le signe d’un nombre et arrondir un nombre.

Représenter un octet sous forme de chaîne

Le Byte type fournit une prise en charge complète des chaînes de format numérique standard et personnalisées. (Pour plus d’informations, consultez Types de mise en forme, chaînes de format numérique standard et chaînes de format numérique personnalisées.) Toutefois, les valeurs d’octets sont généralement représentées sous forme de valeurs à trois chiffres sans mise en forme supplémentaire, ou sous forme de valeurs hexadécimales à deux chiffres.

Pour mettre en forme une Byte valeur en tant que chaîne intégrale sans zéros non significatifs, vous pouvez appeler la méthode sans ToString() paramètre. En utilisant le spécificateur de format « D », vous pouvez également inclure un nombre spécifié de zéros non significatifs dans la représentation sous forme de chaîne. En utilisant le spécificateur de format « X », vous pouvez représenter une Byte valeur sous forme de chaîne hexadécimale. L’exemple suivant met en forme les éléments d’un tableau de Byte valeurs de ces trois façons.

byte[] numbers = { 0, 16, 104, 213 };
foreach (byte number in numbers)
{
    // Display value using default formatting.
    Console.Write("{0,-3}  -->   ", number.ToString());
    // Display value with 3 digits and leading zeros.
    Console.Write(number.ToString("D3") + "   ");
    // Display value with hexadecimal.
    Console.Write(number.ToString("X2") + "   ");
    // Display value with four hexadecimal digits.
    Console.WriteLine(number.ToString("X4"));
}
// The example displays the following output:
//       0    -->   000   00   0000
//       16   -->   016   10   0010
//       104  -->   104   68   0068
//       213  -->   213   D5   00D5
let numbers = [| 0; 16; 104; 213 |]
for number in numbers do
    // Display value using default formatting.
    number.ToString()
    |> printf "%-3s  -->   "

    // Display value with 3 digits and leading zeros.
    number.ToString "D3"
    |> printf "%s   "
    
    // Display value with hexadecimal.
    number.ToString "X2"
    |> printf "%s   "
    
    // Display value with four hexadecimal digits.
    number.ToString "X4"
    |> printfn "%s"

// The example displays the following output:
//       0    -->   000   00   0000
//       16   -->   016   10   0010
//       104  -->   104   68   0068
//       213  -->   213   D5   00D5
Dim numbers() As Byte = {0, 16, 104, 213}
For Each number As Byte In numbers
    ' Display value using default formatting.
    Console.Write("{0,-3}  -->   ", number.ToString())
    ' Display value with 3 digits and leading zeros.
    Console.Write(number.ToString("D3") + "   ")
    ' Display value with hexadecimal.
    Console.Write(number.ToString("X2") + "   ")
    ' Display value with four hexadecimal digits.
    Console.WriteLine(number.ToString("X4"))
Next
' The example displays the following output:
'       0    -->   000   00   0000
'       16   -->   016   10   0010
'       104  -->   104   68   0068
'       213  -->   213   D5   00D5

Vous pouvez également mettre en forme une Byte valeur en tant que chaîne binaire, octal, décimale ou hexadécimale en appelant la ToString(Byte, Int32) méthode et en fournissant la base comme deuxième paramètre de la méthode. L’exemple suivant appelle cette méthode pour afficher les représentations binaires, octales et hexadécimales d’un tableau de valeurs d’octets.

byte[] numbers = { 0, 16, 104, 213 };
Console.WriteLine("{0}   {1,8}   {2,5}   {3,5}",
                  "Value", "Binary", "Octal", "Hex");
foreach (byte number in numbers)
{
    Console.WriteLine("{0,5}   {1,8}   {2,5}   {3,5}",
                      number, Convert.ToString(number, 2),
                      Convert.ToString(number, 8),
                      Convert.ToString(number, 16));
}
// The example displays the following output:
//       Value     Binary   Octal     Hex
//           0          0       0       0
//          16      10000      20      10
//         104    1101000     150      68
//         213   11010101     325      d5
let numbers = [| 0; 16; 104; 213 |]
printfn "%s   %8s   %5s   %5s" "Value" "Binary" "Octal" "Hex"
for number in numbers do
    printfn $"%5i{number}   %8s{Convert.ToString(number, 2)}   %5s{Convert.ToString(number, 8)}   %5s{Convert.ToString(number, 16)}"
                    
// The example displays the following output:
//       Value     Binary   Octal     Hex
//           0          0       0       0
//          16      10000      20      10
//         104    1101000     150      68
//         213   11010101     325      d5
Dim numbers() As Byte = {0, 16, 104, 213}
Console.WriteLine("{0}   {1,8}   {2,5}   {3,5}",
                "Value", "Binary", "Octal", "Hex")
For Each number As Byte In numbers
    Console.WriteLine("{0,5}   {1,8}   {2,5}   {3,5}",
                   number, Convert.ToString(number, 2),
                   Convert.ToString(number, 8),
                   Convert.ToString(number, 16))
Next
' The example displays the following output:
'       Value     Binary   Octal     Hex
'           0          0       0       0
'          16      10000      20      10
'         104    1101000     150      68
'         213   11010101     325      d5

Utiliser des valeurs d’octet non décimales

Outre l’utilisation d’octets individuels comme valeurs décimales, vous pouvez effectuer des opérations au niveau du bit avec des valeurs d’octets, ou utiliser des tableaux d’octets ou avec les représentations binaires ou hexadécimales des valeurs d’octets. Par exemple, les surcharges de la BitConverter.GetBytes méthode peuvent convertir chacun des types de données primitifs en tableau d’octets, et la BigInteger.ToByteArray méthode convertit une BigInteger valeur en tableau d’octets.

Byte les valeurs sont représentées en 8 bits par leur magnitude uniquement, sans bit de signe. Il est important de garder à l’esprit quand vous effectuez des opérations au niveau du bit sur Byte des valeurs ou lorsque vous travaillez avec des bits individuels. Pour effectuer une opération numérique, booléenne ou de comparaison sur deux valeurs non décimales, les deux valeurs doivent utiliser la même représentation.

Lorsqu’une opération est effectuée sur deux Byte valeurs, les valeurs partagent la même représentation, de sorte que le résultat est exact. Ceci est illustré dans l’exemple suivant, qui masque le bit d’ordre le plus bas d’une Byte valeur pour s’assurer qu’il est même.

using System;
using System.Globalization;

public class Example
{
   public static void Main()
   {
      string[] values = { Convert.ToString(12, 16),
                          Convert.ToString(123, 16),
                          Convert.ToString(245, 16) };

      byte mask = 0xFE;
      foreach (string value in values) {
         Byte byteValue = Byte.Parse(value, NumberStyles.AllowHexSpecifier);
         Console.WriteLine("{0} And {1} = {2}", byteValue, mask,
                           byteValue & mask);
      }
   }
}
// The example displays the following output:
//       12 And 254 = 12
//       123 And 254 = 122
//       245 And 254 = 244
open System
open System.Globalization

let values = 
    [ Convert.ToString(12, 16)
      Convert.ToString(123, 16)
      Convert.ToString(245, 16) ]

let mask = 0xFEuy
for value in values do
    let byteValue = Byte.Parse(value, NumberStyles.AllowHexSpecifier)
    printfn $"{byteValue} And {mask} = {byteValue &&& mask}"
                    

// The example displays the following output:
//       12 And 254 = 12
//       123 And 254 = 122
//       245 And 254 = 244
Imports System.Globalization

Module Example1
    Public Sub Main()
        Dim values() As String = {Convert.ToString(12, 16),
                                 Convert.ToString(123, 16),
                                 Convert.ToString(245, 16)}

        Dim mask As Byte = &HFE
        For Each value As String In values
            Dim byteValue As Byte = Byte.Parse(value, NumberStyles.AllowHexSpecifier)
            Console.WriteLine("{0} And {1} = {2}", byteValue, mask,
                           byteValue And mask)
        Next
    End Sub
End Module
' The example displays the following output:
'       12 And 254 = 12
'       123 And 254 = 122
'       245 And 254 = 244

En revanche, lorsque vous travaillez avec des bits non signés et signés, les opérations au niveau du bit sont compliquées par le fait que les SByte valeurs utilisent la représentation de sign-and-magnitude pour les valeurs positives, et la représentation complémentaire de deux pour les valeurs négatives. Pour effectuer une opération significative au niveau du bit, les valeurs doivent être converties en deux représentations équivalentes, et les informations relatives au bit de signe doivent être conservées. L’exemple suivant montre comment masquer les bits 2 et 4 d’un tableau de valeurs signées et non signées 8 bits.

using System;
using System.Collections.Generic;
using System.Globalization;

public struct ByteString
{
    public string Value;
    public int Sign;
}

public class Example1
{
    public static void Main()
    {
        ByteString[] values = CreateArray(-15, 123, 245);

        byte mask = 0x14;        // Mask all bits but 2 and 4.

        foreach (ByteString strValue in values)
        {
            byte byteValue = Byte.Parse(strValue.Value, NumberStyles.AllowHexSpecifier);
            Console.WriteLine("{0} ({1}) And {2} ({3}) = {4} ({5})",
                              strValue.Sign * byteValue,
                              Convert.ToString(byteValue, 2),
                              mask, Convert.ToString(mask, 2),
                              (strValue.Sign & Math.Sign(mask)) * (byteValue & mask),
                              Convert.ToString(byteValue & mask, 2));
        }
    }

    private static ByteString[] CreateArray(params int[] values)
    {
        List<ByteString> byteStrings = new List<ByteString>();

        foreach (object value in values)
        {
            ByteString temp = new ByteString();
            int sign = Math.Sign((int)value);
            temp.Sign = sign;

            // Change two's complement to magnitude-only representation.
            temp.Value = Convert.ToString(((int)value) * sign, 16);

            byteStrings.Add(temp);
        }
        return byteStrings.ToArray();
    }
}
// The example displays the following output:
//       -15 (1111) And 20 (10100) = 4 (100)
//       123 (1111011) And 20 (10100) = 16 (10000)
//       245 (11110101) And 20 (10100) = 20 (10100)
open System
open System.Collections.Generic
open System.Globalization

[<Struct>]
type ByteString =
    { Sign: int
      Value: string }

let createArray values =
    [ for value in values do
        let sign = sign value
        { Sign = sign
         // Change two's complement to magnitude-only representation.
          Value = Convert.ToString(value * sign, 16)} ]


let values = createArray [ -15; 123; 245 ]

let mask = 0x14uy        // Mask all bits but 2 and 4.

for strValue in values do
    let byteValue = Byte.Parse(strValue.Value, NumberStyles.AllowHexSpecifier)
    printfn $"{strValue.Sign * int byteValue} ({Convert.ToString(byteValue, 2)}) And {mask} ({Convert.ToString(mask, 2)}) = {(strValue.Sign &&& (int mask |> sign)) * int (byteValue &&& mask)} ({Convert.ToString(byteValue &&& mask, 2)})"

// The example displays the following output:
//       -15 (1111) And 20 (10100) = 4 (100)
//       123 (1111011) And 20 (10100) = 16 (10000)
//       245 (11110101) And 20 (10100) = 20 (10100)
Imports System.Collections.Generic
Imports System.Globalization

Public Structure ByteString
   Public Value As String
   Public Sign As Integer
End Structure

Module Example2
    Public Sub Main()
        Dim values() As ByteString = CreateArray(-15, 123, 245)

        Dim mask As Byte = &H14        ' Mask all bits but 2 and 4.

        For Each strValue As ByteString In values
            Dim byteValue As Byte = Byte.Parse(strValue.Value, NumberStyles.AllowHexSpecifier)
            Console.WriteLine("{0} ({1}) And {2} ({3}) = {4} ({5})",
                           strValue.Sign * byteValue,
                           Convert.ToString(byteValue, 2),
                           mask, Convert.ToString(mask, 2),
                           (strValue.Sign And Math.Sign(mask)) * (byteValue And mask),
                           Convert.ToString(byteValue And mask, 2))
        Next
    End Sub

    Private Function CreateArray(ParamArray values() As Object) As ByteString()
        Dim byteStrings As New List(Of ByteString)
        For Each value As Object In values
            Dim temp As New ByteString()
            Dim sign As Integer = Math.Sign(value)
            temp.Sign = sign
            ' Change two's complement to magnitude-only representation.
            value = value * sign

            temp.Value = Convert.ToString(value, 16)
            byteStrings.Add(temp)
        Next
        Return byteStrings.ToArray()
    End Function
End Module
' The example displays the following output:
'       -15 (1111) And 20 (10100) = 4 (100)
'       123 (1111011) And 20 (10100) = 16 (10000)
'       245 (11110101) And 20 (10100) = 20 (10100)