Game Development Reference
In-Depth Information
As you can see there are five main types of integers when using C++. It's important to select a
variable that can accommodate all of the possible values you might wish to store. Failing to use a
type with enough possible values results in wrapping. That means that if you had a char variable
that currently stored 127 and you tried to add a one, the value in the variable would wrap and your
variable would then contain -128.
Unsigned Integers
C++ also supports unsigned versions of the integer types shown in Table 2-1 . Table 2-2 shows the
ranges that these unsigned variable types can store.
Table 2-2. MSVC's Unsigned Integral Type Ranges
Type Name
Number of Bytes
Minimum Value
Maximum Value
unsigned char
1
0
255
unsigned short
2
0
65,535
unsigned int
4
0
4,294,967,295
unsigned long
4
0
4,294,967,295
unsigned long long
8
0
18,446,744,073,709,551,615
Using unsigned types extends the range of available positive integers at the expense of losing all
negative integers. These types should be used in all cases where negative numbers will not be needed.
Two's Complement
Before we move on to look at some other types of variables, it is important to understand how
the integer values we have covered are represented by the computer. You've seen that unsigned
numbers of varying numbers of bytes can store numbers ranging from 0 through to their maximum
size. In the case of a single-byte char that maximum number is 255.
This happens because a single byte is made up of 8 individual bits. Each bit represents the next
power of two from the last. Table 2-3 shows how you can think of the bits in a byte.
Table 2-3. The Bits Making Up a Single Byte: The Top Row Shows the Bit Number and the Bottom Row Shows the Value This Byte
Represents When Using Unsigned Variables
8
7
6
5
4
3
2
1
128
64
32
16
8
4
2
1
 
 
Search WWH ::




Custom Search