I\'m just starting out in C++ (literally my second day) and I\'ve been assigned to calculate the ranges of the varying data types, signed and unsigned. The problem is, the way m
In actuality, those ranges can be found in <limits>
- see reference, and specifically the template std::numeric_limits
- see here. I'm assuming though that you want to know where those numbers come from.
What matters is the number of bits. If you have n
bits, then you can express 2n different values with them. Take an old-school 16-bit integer. With 16 bits, the amount of possible different values is 216 = 65536. If you have an unsigned value, you're only expressing non-negative values. So the smallest value you express is 0, and the largest is 2n - 1, so a 16-bit unsigned integer goes from 0
to 65535
.
If you are expressing integers with a sign, then of course you now have the same amount of values (65536 in the previous example) to express some positive and negative numbers. You've got 0
in the middle, and then you split the remaining values between negatives and positives. So you get -32768
on the low end and 32767
on the high end.
For any other datatype that represents an integer, it's the same pattern, whether it's 32, 64 or more bits.
std::numeric_limits<T>
You can get the actual values of these limits using these functions:
You substitute the appropriate type in place of T
, such as signed char
or unsigned char
.
The formulas for a signed number with N bits (using two's complement) are
The formulas for an unsigned number with N bits are
char
The char
has N = 8 bits. Let's verify these formulas with signed char
and unsigned char
.
signed char
unsigned char