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 my school works I won't get to the Math portion where he teaches us the formula for another couple months. He said to get the information from someone who has done the math course already however all of them said they're going to work on this from home where they have their notes. So now I'm left in the dark with google and its inconclusive answers, so I ask you, the wise folk of stackoverflow.
What are the formulas for getting the range of the data types? I have found one for INT that has worked but does not apply to the others, the ones he wants us to calculate are: char, short, long, and long long. He also wants the unsigned versions of those 4 as well as INT.
We already have the size in bits and bytes of each of these data types.
Here is how I have my INT range laid out:
printf ("\nThe range of int is: %f\n", pow(2, (sizeof(int) * CHAR_BIT) -1));
std::numeric_limits<T>
You can get the actual values of these limits using these functions:
T std::numeric_limits<T>::min()
T std::numeric_limits<T>::max()
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With