math - Formula to determine the range of signed and unsigned data types C++ -
i'm starting out in c++ (literally second day) , i've been assigned calculate ranges of varying data types, signed , unsigned. problem is, way school works won't math portion teaches formula couple months. said information has done math course of them said they're going work on home have notes. i'm left in dark google , inconclusive answers, ask you, wise folk of stackoverflow.
what formulas getting range of data types? have found 1 int has worked not apply others, ones wants calculate are: char, short, long, , long long. wants unsigned versions of 4 int.
we have size in bits , bytes of each of these data types.
here how have 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 actual values of these limits using these functions:
you substitute appropriate type in place of t
, such signed char
or unsigned char
.
formulas
the formulas signed number n bits (using two's complement) are
- min = -1 * 2n - 1
- max = 2n - 1 - 1
the formulas unsigned number n bits are
- min = 0
- max = 2n - 1
example: 8-bit char
the char
has n = 8 bits. let's verify these formulas signed char
, unsigned char
.
signed char
- min = -1 * 2n - 1 = -1 * 27 = -128
- max = 2n - 1 - 1 = 27 - 1 = 127
unsigned char
- min = 0
- max = 2n - 1 = 28 - 1 = 255
Comments
Post a Comment