閱讀英文

共用方式為


System.Byte 結構

本文提供此 API 參考文件的補充備註。

Byte是不可變的實值類型,表示不帶正負號的整數,其值範圍從 0(以常數表示)到 255(Byte.MinValue以常數表示)。Byte.MaxValue .NET 也包含帶正負號的 8 位整數實值型別, SByte代表範圍從 -128 到 127 的值。

具現化 Byte 值

您可以透過數種方式具現化 Byte 值:

  • 您可以宣告 Byte 變數,併為其指派數據類型範圍內的 Byte 常值整數值。 下列範例會宣告兩個 Byte 變數,並以這種方式指派這些變數。

    C#
    byte value1 = 64;
    byte value2 = 255;
    
  • 您可以將非位元組數值指派給位元組。 這是縮小轉換,因此它需要 C# 和 F# 中的轉換運算符,或 Visual Basic 中的轉換方法。Option Strict 如果非位元組值是包含 Single小數元件的、 DoubleDecimal 值,則其小數部分的處理取決於執行轉換的編譯程式。 下列範例會將數個數值指派給 Byte 變數。

    C#
    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
    
  • 您可以呼叫 類別的 Convert 方法,將任何支援的型 Byte 別轉換為值。 這是可能的,因為 Byte 支援 IConvertible 介面。 下列範例說明如何將值Byte陣列Int32轉換成值。

    C#
    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.
    
  • 您可以呼叫 ParseTryParse 方法,將值的字串表示 Byte 轉換成 Byte。 字串可以包含十進位或十六進位數位。 下列範例說明使用十進位和十六進位字串來剖析作業。

    C#
    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
    

對 Byte 值執行作業

Byte 類型支援標準數學運算,例如加法、減法、除法、乘法、減法、負數和一元否定。 如同其他整數型別,此 Byte 類型也支援位 AND、、 ORXOR左移和右移運算符。

您可以使用標準數值運算符來比較兩個 Byte 值,也可以呼叫 CompareToEquals 方法。

您也可以呼叫 類別的成員 Math 來執行廣泛的數值運算,包括取得數字的絕對值、計算整數除數的商數和餘數、判斷兩個整數的最大值或最小值、取得數位的正負號,以及四捨五入數位。

將位元組表示為字串

Byte 類型提供標準和自定義數值格式字串的完整支援。 (如需詳細資訊,請參閱 格式化類型標準數值格式字串自定義數值格式字串。)不過,最常見的是,位元組值會以一位數到三位數的值表示,而不需要任何額外的格式設定,或以兩位數十六進位值表示。

若要將 Byte 值格式化為不含前置零的整數位符串,您可以呼叫無 ToString() 參數方法。 藉由使用 「D」 格式規範,您也可以在字串表示中包含指定數目的前置零。 藉由使用 「X」 格式規範,您可以將值表示 Byte 為十六進位字串。 下列範例會以下列三種方式格式化值陣列 Byte 中的元素。

C#
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

您也可以呼叫 ToString(Byte, Int32) 方法,並提供基底做為方法的第二個參數,將值格式化Byte為二進位、八進位、十六進位或十六進位字串。 下列範例會呼叫這個方法,以顯示位元組值陣列的二進位、八進位和十六進位表示法。

C#
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

使用非十進位位元組值

除了使用個別位元組做為十進位值之外,您可能還想要使用位元組值執行位運算,或是使用位元組陣列,或是使用位元組值的二進位或十六進位表示法。 例如,方法的多 BitConverter.GetBytes 載可以將每個基本數據類型轉換成位元組陣列,而 BigInteger.ToByteArray 方法會將 BigInteger 值轉換成位元組陣列。

Byte 值僅以 8 位表示,不含符號位。 當您對 Byte 值執行位運算或處理個別位時,請務必記住這點。 若要在任何兩個非十進位值上執行數值、布爾值或比較運算,這兩個值都必須使用相同的表示法。

當作業在兩 Byte 個值上執行時,這些值會共用相同的表示法,因此結果正確無誤。 在下列範例中會說明這一點,它會遮罩值的最低順序位 Byte ,以確保它偶數也一樣。

C#
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

另一方面,當您同時使用不帶正負號和帶正負號位時,位運算很複雜 SByte ,因為值會使用正值的符號和大小表示,以及兩者的負值補碼表示。 若要執行有意義的位運算,值必須轉換成兩個對等表示法,而且必須保留符號位的相關信息。 下列範例會執行此動作,以遮罩 8 位帶正負號和不帶正負號值的陣列 2 和 4 位。

C#
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)