|Important||This document may not represent best practices for current development, links to downloads and other resources may no longer be valid. Current recommended version can be found here. ArchiveDisclaimer|
Byte Data Type (Visual Basic)
Updated: October 2008
Holds unsigned 8-bit (1-byte) integers that range in value from 0 through 255.
Use the Byte data type to contain binary data.
The default value of Byte is 0.
Negative Numbers. Because Byte is an unsigned type, it cannot represent a negative number. If you use the unary minus (-) operator on an expression that evaluates to type Byte, Visual Basic converts the expression to Short first.
Format Conversions. When Visual Basic reads or writes files, or when it calls DLLs, methods, and properties, it can automatically convert between data formats. Binary data stored in Byte variables and arrays is preserved during such format conversions. You should not use a String variable for binary data, because its contents can be corrupted during conversion between ANSI and Unicode formats.
Widening. The Byte data type widens to Short, UShort, Integer, UInteger, Long, ULong, Decimal, Single, or Double. This means you can convert Byte to any of these types without encountering a System.OverflowException error.
Type Characters. Byte has no literal type character or identifier type character.
Framework Type. The corresponding type in the .NET Framework is the System.Byte structure.
In the following example, b is a Byte variable. The statements demonstrate the range of the variable and the application of bit-shift operators to it.
' 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)