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

后端 未结 2 678
清歌不尽
清歌不尽 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:04

    std::numeric_limits

    You can get the actual values of these limits using these functions:

    • T std::numeric_limits::min()
    • T std::numeric_limits::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

提交回复
热议问题