Byte 数据类型(Visual Basic)

保存 8 位(1 字节)无符号整数,值的范围为 0 到 255。

注解

使用 Byte 数据类型来包含二进制数据。

Byte 的默认值为 0。

文本赋值

可以通过为其分配十进制文本、十六进制文本、八进制文本或(从 Visual Basic 2017 开始)二进制文本来声明和初始化 Byte 变量。 如果整数文本在 Byte 范围之外(即,如果它小于 Byte.MinValue 或大于 Byte.MaxValue),会发生编译错误。

在以下示例中,表示为十进制、十六进制和二进制文本的等于 201 的整数从 整数 隐式转换为 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 格式之间进行转换时,可能会损坏其内容。

  • Widening。 Byte 数据类型加宽到 ShortUShortIntegerUIntegerLongULongDecimalSingleDouble。 这意味着,你可以将 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)

另请参阅