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

后端 未结 2 644
清歌不尽
清歌不尽 2021-02-02 17:48

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

相关标签:
2条回答
  • 2021-02-02 18:02

    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.

    0 讨论(0)
  • 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
    0 讨论(0)
提交回复
热议问题