整数类型可以在 C++ 中存储的值范围是多少

2022-01-14 00:00:00 int c++

unsigned long int 能否在 32 位计算机上保存十位数字 (1,000,000,000 - 9,999,999,999)?

Can unsigned long int hold a ten digits number (1,000,000,000 - 9,999,999,999) on a 32-bit computer?

另外,unsigned long intlong intunsigned intshort int的范围是多少, short unsigned int, 和 int?

Additionally, what are the ranges of unsigned long int , long int, unsigned int, short int, short unsigned int, and int?

推荐答案

您可以依赖的最小范围是:

  • short intint:-32,767 到 32,767
  • unsigned short intunsigned int:0 到 65,535
  • long int:-2,147,483,647 到 2,147,483,647
  • unsigned long int:0 到 4,294,967,295
  • short int and int: -32,767 to 32,767
  • unsigned short int and unsigned int: 0 to 65,535
  • long int: -2,147,483,647 to 2,147,483,647
  • unsigned long int: 0 to 4,294,967,295

这意味着不,long int 不能用来存储任何 10 位数字.然而,更大的类型 long long int 在 C99 和 C++11 中被引入到 C 和 C++ 中(这种类型通常也被为不包括它的旧标准构建的编译器作为扩展支持).如果您的编译器支持,此类型的最小范围是:

This means that no, long int cannot be relied upon to store any 10 digit number. However, a larger type long long int was introduced to C in C99 and C++ in C++11 (this type is also often supported as an extension by compilers built for older standards that did not include it). The minimum range for this type, if your compiler supports it, is:

  • long long int:-9,223,372,036,854,775,807 到 9,223,372,036,854,775,807
  • unsigned long long int:0 到 18,446,744,073,709,551,615
  • long long int: -9,223,372,036,854,775,807 to 9,223,372,036,854,775,807
  • unsigned long long int: 0 to 18,446,744,073,709,551,615

所以该类型将足够大(再次,如果你有它可用).

So that type will be big enough (again, if you have it available).

对于那些认为我对这些下限犯了错误的人的说明:编写范围的 C 要求是为了允许一个的补码或符号大小整数表示,其中最低可表示值和最高可表示值仅在符号上不同.还允许使用二进制补码表示,其中符号位为 1 且所有值位为 0 的值是 陷阱表示,而不是合法值.换句话说,int 不需要 能够表示值 -32,768.

A note for those who believe I've made a mistake with these lower bounds: the C requirements for the ranges are written to allow for ones' complement or sign-magnitude integer representations, where the lowest representable value and the highest representable value differ only in sign. It is also allowed to have a two's complement representation where the value with sign bit 1 and all value bits 0 is a trap representation rather than a legal value. In other words, int is not required to be able to represent the value -32,768.

相关文章