Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Formula to determine the range of signed and unsigned data types C++

Tags:

c++

math

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));
like image 331
Andrew B Avatar asked Aug 07 '13 19:08

Andrew B


1 Answers

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.

Formulas

The formulas for a signed number with N bits (using two's complement) are

  • min = -1 * 2N - 1
  • max = 2N - 1 - 1

The formulas for an unsigned number with N bits are

  • min = 0
  • max = 2N - 1

Example: 8-bit char

The char has N = 8 bits. Let's verify these formulas with signed char and 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
like image 137
Timothy Shields Avatar answered Oct 16 '22 16:10

Timothy Shields