None of the previous numeric types is stored in a single byte. In some situations, however, data are stored as bytes, and you must be able to access individual bytes. The Byte data type holds an integer in the range of 0 to 255. Bytes are frequently used to access binary files, image and sound files, and so on. Note that you no longer use bytes to access individual characters. Unicode characters are stored in two bytes.
To declare a variable as a Byte, use the following statement:
Dim n As Byte
Code language: VB.NET (vbnet)
The variable n can be used in numeric calculations too, but you must be careful not to assign the result to another Byte variable if its value might exceed the range of the Byte type. If the variables A and B are initialized as follows:
Dim A As Byte, B As Byte
A = 233
B = 50
Code language: VB.NET (vbnet)
the following statement will produce an overflow exception:
Debug.WriteLine(A + B)
Code language: VB.NET (vbnet)
The same will happen if you attempt to assign this value to a Byte variable with the following statement:
B = A + B
Code language: VB.NET (vbnet)
The result (283) can’t be stored in a single byte. Visual Basic generates the correct answer, but it can’t store it into a Byte variable.
In addition to the Byte data type, VB 2008 provides a Signed Byte data type, SByte, which can represent signed values in the range from −128 to 127. The bytes starting with the 1 bit represent negative values. The range of positive values is less by one than the range of values of negative values, because the value 0 is considered a positive value (its first bit is 0).
Boolean Operations with Bytes
The operators that won’t cause overflows are the Boolean operators AND, OR, NOT, and XOR, which are frequently used with Byte variables. These aren’t logical operators that return True or False; they combine the matching bits in the two operands and return another byte. If you combine the numbers 199 and 200 with the AND operator, the result is 192. The two values in binary format are 11000111 and 11001000. If you perform a bitwise AND operation on these two values, the result is 11000000, which is the decimal value 192.