Byte 資料類型 (Visual Basic)

保存帶正負號的 8 位元 (1 位元組) 整數,值的範圍從 0 到 255。

備註

使用 Byte 資料類型,以包含二進位資料。

Byte 的預設值為 0。

常值指派

您可以透過將十進位常值、十六進位常值、八進位常值或二進位常值 (自 Visual Basic 2017 起) 指派給 Byte 變數,以將其宣告和初始化。 如果整數常值超出 Byte 的範圍 (亦即,如果小於 Byte.MinValue 或大於 Byte.MaxValue),就會發生編譯錯誤。

在下列範例中,整數等於以十進位、十六進位和二進位常值表示 201,從 integer 隱含轉換成 byte 值。

Dim byteValue1 As Byte = 201
Console.WriteLine(byteValue1)

Dim byteValue2 As Byte = &H00C9
Console.WriteLine(byteValue2)

Dim byteValue3 As Byte = &B1100_1001
Console.WriteLine(byteValue3)
' The example displays the following output:
'          201
'          201
'          201

注意

您可以使用 &h&H 前置詞來表示十六進位常值,以 &b&B 前置詞來表示二進位常值,以 &o&O 前置詞來表示八進位常值。 十進位常值沒有前置詞。

自 Visual Basic 2017 開始,您也可以使用底線字元 (_) 作為數字分隔符號,以提升可讀性,如下列範例所示。

Dim byteValue3 As Byte = &B1100_1001
Console.WriteLine(byteValue3)
' The example displays the following output:
'          201

從 Visual Basic 15.5 開始,您也可以使用底線字元 (_) 作為前置字元與十六進位、二進位或八進位數字之間的前置分隔符號。 例如:

Dim number As Byte = &H_6A

若要使用底線字元作為前置分隔符號,您必須將下列項目新增至 Visual Basic 專案 (*.vbproj) 檔:

<PropertyGroup>
  <LangVersion>15.5</LangVersion>
</PropertyGroup>

如需詳細資訊,請參閱選取 Visual Basic 語言版本

程式設計提示

  • 負數。 因為 Byte 為不帶正負號的型別,所以無法代表負數。 如果您在評估 Byte 類別的運算式上使用一元減號 (-) 運算子,則 Visual Basic 會先將運算式轉換成 Short

  • 資料格式轉換。 當 Visual Basic 讀取或寫入檔案,或呼叫 DLL、方法和屬性時,它可以在資料格式之間自動轉換。 儲存在 Byte 變數和陣列中的二進位資料會在這類格式轉換期間保留。 您不應該將 String 變數用於二進位資料,因為在 ANSI 和 Unicode 格式之間的轉換期間其內容可能會損毀。

  • 擴展。 Byte 資料類型可擴展為 ShortUShortIntegerUIntegerLongULongDecimalSingle,或 Double。 這表示,您可以將 Byte 轉換成這些類型的任何一種,而不會發生 System.OverflowException 錯誤。

  • 類型字元。 Byte 沒有常值型別字元或識別項型別字元。

  • Framework 類型。 在 .NET Framework 中對應的類型為 System.Byte 結構。

範例

在下列範例中,bByte 變數。 陳述式示範變數的範圍,以及陳述式之位元移位運算子的應用程式。

' The valid range of a Byte variable is 0 through 255.
Dim b As Byte
b = 30
' The following statement causes an error because the value is too large.
'b = 256
' The following statement causes an error because the value is negative.
'b = -5
' The following statement sets b to 6.
b = CByte(5.7)

' The following statements apply bit-shift operators to b.
' The initial value of b is 6.
Console.WriteLine(b)
' Bit shift to the right divides the number in half. In this 
' example, binary 110 becomes 11.
b >>= 1
' The following statement displays 3.
Console.WriteLine(b)
' Now shift back to the original position, and then one more bit
' to the left. Each shift to the left doubles the value. In this
' example, binary 11 becomes 1100.
b <<= 2
' The following statement displays 12.
Console.WriteLine(b)

另請參閱