Recipe 6.3. Using Unsigned Integers


Problem

You want to work with nonnegative integers while minimizing the memory requirements of variables in your code.

Solution

Use the smallest unsigned integer variable types that will hold the desired range of nonnegative values.

Discussion

As mentioned in the previous recipe, the unsigned integer variable types provide many new options for working with nonnegative integers in Visual Basic 2005. The following code provides a specific example to help clarify the concept:

 Dim testUShort As UShort Do Until (testUShort > CUShort(33000))    testUShort += CUShort(1) Loop MsgBox("UShort result: " & testUShort.ToString()) 

The standard Visual Basic Short variable type holds signed integers in the range -32,768 to +32,767 and uses only two bytes of memory. If the previous code used signed integers, an exception would be generated during the looping because values up to 33,001 are not allowed. The unsigned testUShort integer stores values up to 65,535, so the program runs successfully, and the variable still requires only two bytes of memory. Figure 6-3 shows a two-byte unsigned variable displaying a number too big for a standard signed two-byte integer.

Figure 6-3. Unsigned integer variables can hold bigger numbers than signed integers, in the same amount of memory


See Also

Search for "UInteger" in Visual Studio Help for more information.




Visual Basic 2005 Cookbook(c) Solutions for VB 2005 Programmers
Visual Basic 2005 Cookbook: Solutions for VB 2005 Programmers (Cookbooks (OReilly))
ISBN: 0596101775
EAN: 2147483647
Year: 2006
Pages: 400

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net