System.Byte 结构

本文提供了此 API 参考文档的补充说明。

Byte 是一个不可变值类型,表示无符号整数,其值范围为 0(由常量表示 Byte.MinValue )到 255(由常量表示 Byte.MaxValue )。 .NET 还包含有符号 8 位整数值类型, SByte表示介于 -128 到 127 之间的值。

实例化字节值

可以通过多种方式实例化 Byte 值:

  • 可以声明变量 Byte ,并为其分配数据类型范围内的 Byte 文本整数值。 以下示例声明两个 Byte 变量,并以此方式为其分配值。

    byte value1 = 64;
    byte value2 = 255;
    
    let value1 = 64uy
    let value2 = 255uy
    
    Dim value1 As Byte = 64
    Dim value2 As Byte = 255
    
  • 可以将非字节数值分配给字节。 这是一个缩小的转换,因此它需要 C# 和 F# 中的强制转换运算符,或者 Visual Basic 中的转换方法(如果 Option Strict 已打开)。 如果非字节值是包含SingleDouble小数部分的值,Decimal则其小数部分的处理取决于执行转换的编译器。 以下示例将多个数值分配给 Byte 变量。

    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
    
  • 可以调用类的方法 Convert ,将任何受支持的类型转换为 Byte 值。 这是可能的,因为 Byte 支持 IConvertible 接口。 下面的示例演示了值数组 Int32Byte 值的转换。

    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.
    
  • 可以调用ParseTryParse方法将值的字符串表示形式Byte转换为 。Byte 该字符串可以包含十进制或十六进制数字。 以下示例使用十进制字符串和十六进制字符串演示了分析操作。

    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
    

对字节值执行操作

Byte 类型支持标准数学运算,例如加法、减法、除法、乘法、减法、求反和一元求反。 与其他整型类型一样,该 Byte 类型还支持位 ANDORXOR左移和右移运算符。

可以使用标准数值运算符比较两个 Byte 值,也可以调用 CompareToEquals 方法。

还可以调用类的成员 Math 来执行广泛的数值运算,包括获取数字的绝对值、计算整数除法的商数和余数、确定两个整数的最大值或最小值、获取数字的符号以及舍入数字。

将字节表示为字符串

Byte 类型为标准和自定义数字格式字符串提供完全支持。 (有关详细信息,请参阅 格式设置类型标准数字格式字符串自定义数字格式字符串。但是,通常,字节值表示为一位数到三位数的值,没有任何附加格式,或者表示为两位数十六进制值。

若要将 Byte 值格式化为无前导零的整型字符串,可以调用无 ToString() 参数方法。 通过使用“D”格式说明符,还可以在字符串表示形式中包含指定数量的前导零。 通过使用“X”格式说明符,可以将值 Byte 表示为十六进制字符串。 以下示例采用以下三种方式设置值数组 Byte 中的元素的格式。

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

还可以通过调用ToString(Byte, Int32)该方法并提供基作为方法的第二个参数,将值格式化Byte为二进制、八进制、十六进制或十六进制字符串。 以下示例调用此方法以显示字节值的数组的二进制、八进制和十六进制表示形式。

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

使用非十进制字节值

除了将单个字节用作十进制值之外,你可能还希望对字节值执行按位运算,或者使用字节数组或字节值的二进制或十六进制表示形式。 例如,该方法的 BitConverter.GetBytes 重载可以将每个基元数据类型转换为字节数组,并且 BigInteger.ToByteArray 该方法将值转换为 BigInteger 字节数组。

Byte 值仅以 8 位表示,不带符号位。 在对 Byte 值执行按位操作或处理单个位时,请务必记住这一点。 若要对任何两个非十进制值执行数值、布尔或比较运算,这两个值都必须使用相同的表示形式。

对两 Byte 个值执行操作时,这些值共享相同的表示形式,因此结果准确。 以下示例对此进行了说明,该示例屏蔽了值 Byte 的最低顺序位,以确保它均匀。

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

另一方面,使用无符号位和带符号位时,按位运算很复杂,因为 SByte 值对正值使用符号和数量级表示形式,以及两者的负值的补充表示形式。 若要执行有意义的按位运算,必须将值转换为两个等效表示形式,并且必须保留有关符号位的信息。 以下示例执行此操作以屏蔽 8 位有符号值和无符号值的数组中的 2 位和 4 位。

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)