-
C++ Types 3
Posted on May 2nd, 2009 No commentsInteger Types
Unsigned integer types
These types only vary in the amount of bits they use to represent numbers. The numbers are encoded in the bits as binary. C++03 mandates a set of unsigned integer types and a minimum number of bits and range for each type. The actual number of bits is implementation specific as long as it follows the following rules
- (for the number of bits of each) unsigned char <= unsigned short int <= unsigned int <= unsigned long int.
- char (and thus unsigned char) has enough bits to store the basic character set.
- int has the “natural” bit size of the architecture (Usually 16, 32 or 64 bits)
Type
C++03 minimum bits
C++03 Minimum range
VS2008 bits
VS2008 Range
unsigned char
8
0-255
8
0-255
unsigned short int
16
0-65535
16
0-65535
unsigned int
16
0-65535
32
0-4294967295
unsigned long int
32
0-4294967295
32
0-4294967295
It is interesting to note that the following condition is legal in a C++ implementation:
- The number of bits in the following types can all be equal: unsigned char = unsigned short int = unsigned int = unsigned long int (It would have to be at least 32 bits to satisfy the standard)
- For example the following is legal:
Type
Bits
Range
unsigned char
60
0-1152921504606846976
unsigned short int
60
0-1152921504606846976
unsigned int
60
0-1152921504606846976
unsigned long int
60
0-1152921504606846976
Signed integer types
Signed integer types can be encoded in three different ways, sign magnitude, 1’s complement and 2’s complement. The C++03 standard allows an implementation to use any of these representations. However most implementations use 2’s complement. 2’s complement is really easy to understand, it’s just like the normal unsigned binary representation, except the highest digit represents the negation of the power of 2 of it’s position. For example 1011 means 1*(-8) + 0*4 + 1*2 + 1 = -8 + 2 + 1 = -5.
The signed types follow the same rules as the unsigned types (see above) and the ranges are as follows:
Type
C++03 minimum bits
C++03 Minimum range
VS2008 bits
VS2008 Range
signed char
8
-127 – 127
8
-128 – 127
short int
16
-32767 – 32767
16
-32768 – 32767
int
16
-32767 – 32767
32
-2147483648 – 2147483647
long int
32
-2147483647 – 2147483647
32
-2147483648 – 2147483647
chars
There are some special rules for chars. In many ways char is the “base” type of a C++ system. It’s the smallest addressable set of bits when programming in C or C++. Other types’ sizes are always measured in terms of chars, sizeof(T) returns the number of chars needed to store T.
- char, signed char and unsigned char types must:
- All have the same alignment requirements and have the same number of bits.
- Large enough to represent the basic character set.
- char can either be signed or unsigned, it depends on the implementation.
- VS2008 uses signed chars by default.
Leave a reply


