# Byte 結構

## 定義

public value class Byte : IComparable, IComparable<System::Byte>, IConvertible, IEquatable<System::Byte>, IFormattable
[System.Runtime.InteropServices.ComVisible(true)]
[System.Serializable]
public struct Byte : IComparable, IComparable<byte>, IConvertible, IEquatable<byte>, IFormattable
type byte = struct
interface IFormattable
interface IConvertible
Public Structure Byte
Implements IComparable, IComparable(Of Byte), IConvertible, IEquatable(Of Byte), IFormattable

## 備註

Byte 是不可變的實值型別，代表值範圍從0（由 Byte.MinValue 常數表示）到255（以 Byte.MaxValue 常數表示）的不帶正負號的整數。Byte is an immutable value type that represents unsigned integers with values that range from 0 (which is represented by the Byte.MinValue constant) to 255 (which is represented by the Byte.MaxValue constant). .NET Framework 也包含帶正負號的8位整數數值型別（SByte），其代表的值範圍從-128 到127。The .NET Framework also includes a signed 8-bit integer value type, SByte, which represents values that range from -128 to 127.

### 將位元組值具現化Instantiating a Byte Value

• 您可以宣告 Byte 變數，並為其指派在 Byte 資料類型範圍內的常值整數值。You can declare a Byte variable and assign it a literal integer value that is within the range of the Byte data type. 下列範例會宣告兩個 Byte 變數，並以這種方式指派值給它們。The following example declares two Byte variables and assigns them values in this way.

byte value1 = 64;
byte value2 = 255;

Dim value1 As Byte = 64
Dim value2 As Byte = 255

• 您可以將非位元組數值指派給 byte。You can assign a non-byte numeric value to a byte. 這是縮小轉換，因此如果 Option Strict 是 on，則需要C#在中使用 cast 運算子，並在 Visual Basic 中使用轉換方法。This is a narrowing conversion, so it requires a cast operator in C# and a conversion method in Visual Basic if Option Strict is on. 如果非位元組值是包含小陣列件的 SingleDoubleDecimal 值，則處理其小數部分取決於執行轉換的編譯器。If the non-byte value is a Single, Double, or Decimal value that includes a fractional component, the handling of its fractional part depends on the compiler performing the conversion. 下列範例會將數個數值指派給 Byte 變數。The following example assigns several numeric values to 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

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 值。You can call a method of the Convert class to convert any supported type to a Byte value. 這是可能的，因為 Byte 支援 IConvertible 介面。This is possible because Byte supports the IConvertible interface. 下列範例說明如何將 Int32 值陣列轉換成 Byte 值。The following example illustrates the conversion of an array of Int32 values to Byte values.

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.

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 值的字串表示轉換成 ByteYou can call the Parse or TryParse method to convert the string representation of a Byte value to a Byte. 字串可以包含十進位或十六進位數位。The string can contain either decimal or hexadecimal digits. 下列範例說明使用十進位和十六進位字串的剖析作業。The following example illustrates the parse operation by using both a decimal and a hexadecimal string.

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

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

### 執行位元組值的作業Performing Operations on Byte Values

Byte 類型支援標準的數學運算，例如加法、減法、除法、乘法、減法、否定和一元否定。The Byte type supports standard mathematical operations such as addition, subtraction, division, multiplication, subtraction, negation, and unary negation. 就像其他整數類型一樣，Byte 類型也支援位 ANDORXOR、左移和右移位運算子。Like the other integral types, the Byte type also supports the bitwise AND, OR, XOR, left shift, and right shift operators.

### 將位元組表示為字串Representing a Byte as a String

Byte 類型提供標準和自訂數值格式字串的完整支援。The Byte type provides full support for standard and custom numeric format strings. （如需詳細資訊，請參閱格式化類型標準數值格式字串自訂數值格式字串。）不過，最常見的位元組值會表示為一位數到三位數的值，而不需要任何額外的格式，或做為兩位數的十六進位值。(For more information, see Formatting Types, Standard Numeric Format Strings, and Custom Numeric Format Strings.) However, most commonly, byte values are represented as one-digit to three-digit values without any additional formatting, or as two-digit hexadecimal values.

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") + "   ");
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
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") + "   ")
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

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

### 使用非十進位的位元組值Working with Non-Decimal Byte Values

Byte 值只會以其大小以8位表示，不含正負號位。Byte values are represented in 8 bits by their magnitude only, without a sign bit. 當您在 Byte 值上執行位運算，或使用個別位時，請務必記住這一點。This is important to keep in mind when you perform bitwise operations on Byte values or when you work with individual bits. 若要在任何兩個非十進位值上執行數值、布林值或比較運算，這兩個值都必須使用相同的標記法。In order to perform a numeric, Boolean, or comparison operation on any two non-decimal values, both values must use the same representation.

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) };

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

Module Example
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, _
Next
End Sub
End Module
' The example displays the following output:
'       12 And 254 = 12
'       123 And 254 = 122
'       245 And 254 = 244

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

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

public class Example
{
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),
}
}

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);

}
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)
Imports System.Collections.Generic
Imports System.Globalization

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

Module Example
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), _
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)
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)

## 欄位

 表示 Byte 最大的可能值。Represents the largest possible value of a Byte. 這個欄位為常數。This field is constant. 表示 Byte 最小的可能值。Represents the smallest possible value of a Byte. 這個欄位為常數。This field is constant.

## 方法

 將這個執行個體與指定的 8 位元不帶正負號的整數相比較，並傳回它們的相對值指示。Compares this instance to a specified 8-bit unsigned integer and returns an indication of their relative values. 將這個執行個體與指定的物件相比較，並傳回它們的相對值指示。Compares this instance to a specified object and returns an indication of their relative values. 傳回值，該值表示這個執行個體和指定的 Byte 物件是否代表相同值。Returns a value indicating whether this instance and a specified Byte object represent the same value. 傳回值，該值表示這個執行個體是否和指定的物件相等。Returns a value indicating whether this instance is equal to a specified object. 傳回這個執行個體的雜湊碼。Returns the hash code for this instance. 傳回實值類型 TypeCode 的 Byte。Returns the TypeCode for value type Byte. 將指定樣式和特定文化特性格式的數字範圍轉換為其對等 Byte。Converts the span representation of a number in a specified style and culture-specific format to its Byte equivalent. 將數字的字串表示，轉換為其相等的 Byte。Converts the string representation of a number to its Byte equivalent. 將使用指定特定文化特性格式之數字的字串表示轉換為其相等的 Byte。Converts the string representation of a number in a specified culture-specific format to its Byte equivalent. 將指定樣式中數字的字串表示轉換為其相等的 Byte。Converts the string representation of a number in a specified style to its Byte equivalent. 將數字的字串表示 (使用指定樣式和特定文化特性的格式) 轉換為其相等的 Byte。Converts the string representation of a number in a specified style and culture-specific format to its Byte equivalent. 將目前 Byte 物件的值，轉換為其相等的字串表示。Converts the value of the current Byte object to its equivalent string representation. 使用指定的特定文化特性格式資訊，將目前 Byte 物件的數值轉換為其相等的字串表示。Converts the numeric value of the current Byte object to its equivalent string representation using the specified culture-specific formatting information. 使用指定的格式，將目前 Byte 物件的值，轉換為其相等字串表示。Converts the value of the current Byte object to its equivalent string representation using the specified format. 使用指定的格式和特定文化特性的格式資訊，將目前 Byte 物件的值，轉換為其相等的字串表示。Converts the value of the current Byte object to its equivalent string representation using the specified format and culture-specific formatting information. 嘗試將目前不帶正負號的 8 位元整數執行個體值格式化為所提供字元範圍。Tries to format the value of the current 8-bit unsigned integer instance into the provided span of characters. 嘗試將數字的範圍表示轉換為其對等的 Byte，並傳回值以指出轉換是否成功。Tries to convert the span representation of a number to its Byte equivalent, and returns a value that indicates whether the conversion succeeded. 將指定樣式和特定文化特性格式的數字範圍轉換為其對等 Byte。Converts the span representation of a number in a specified style and culture-specific format to its Byte equivalent. 傳回值，該值指出轉換成功或失敗。A return value indicates whether the conversion succeeded or failed. 嘗試將數字的字串表示轉換成其相等的 Byte，並傳回一個值表示轉換是否成功。Tries to convert the string representation of a number to its Byte equivalent, and returns a value that indicates whether the conversion succeeded. 將數字的字串表示 (使用指定樣式和特定文化特性的格式) 轉換為其相等的 Byte。Converts the string representation of a number in a specified style and culture-specific format to its Byte equivalent. 傳回值，該值指出轉換成功或失敗。A return value indicates whether the conversion succeeded or failed.

## 明確介面實作

 如需這個成員的說明，請參閱 ToBoolean(IFormatProvider)。For a description of this member, see ToBoolean(IFormatProvider). 如需這個成員的說明，請參閱 ToByte(IFormatProvider)。For a description of this member, see ToByte(IFormatProvider). 如需這個成員的說明，請參閱 ToChar(IFormatProvider)。For a description of this member, see ToChar(IFormatProvider). 不支援此轉換。This conversion is not supported. 嘗試使用這個方法會擲回 InvalidCastException。Attempting to use this method throws an InvalidCastException. 如需這個成員的說明，請參閱 ToDecimal(IFormatProvider)。For a description of this member, see ToDecimal(IFormatProvider). 如需這個成員的說明，請參閱 ToDouble(IFormatProvider)。For a description of this member, see ToDouble(IFormatProvider). 如需這個成員的說明，請參閱 ToInt16(IFormatProvider)。For a description of this member, see ToInt16(IFormatProvider). 如需這個成員的說明，請參閱 ToInt32(IFormatProvider)。For a description of this member, see ToInt32(IFormatProvider). 如需這個成員的說明，請參閱 ToInt64(IFormatProvider)。For a description of this member, see ToInt64(IFormatProvider). 如需這個成員的說明，請參閱 ToSByte(IFormatProvider)。For a description of this member, see ToSByte(IFormatProvider). 如需這個成員的說明，請參閱 ToSingle(IFormatProvider)。For a description of this member, see ToSingle(IFormatProvider). 如需這個成員的說明，請參閱 ToType(Type, IFormatProvider)。For a description of this member, see ToType(Type, IFormatProvider). 如需這個成員的說明，請參閱 ToUInt16(IFormatProvider)。For a description of this member, see ToUInt16(IFormatProvider). 如需這個成員的說明，請參閱 ToUInt32(IFormatProvider)。For a description of this member, see ToUInt32(IFormatProvider). 如需這個成員的說明，請參閱 ToUInt64(IFormatProvider)。For a description of this member, see ToUInt64(IFormatProvider).