【发布时间】:2010-12-16 11:07:44
【问题描述】:
是否有 C++ 跨平台库为我提供可移植的最大整数?
我要声明:
const int MAX_NUM = /* call some library here */;
我使用非托管的 MSVC 2008。
【问题讨论】:
-
你不需要lib,你需要学习C++;你要的是标准 c++ (std::numeric_limits)
标签: c++
是否有 C++ 跨平台库为我提供可移植的最大整数?
我要声明:
const int MAX_NUM = /* call some library here */;
我使用非托管的 MSVC 2008。
【问题讨论】:
标签: c++
在C++标准库头<limits>中,你会发现:
std::numeric_limits<int>::max()
这将告诉您可以存储在int 类型变量中的最大值。 numeric_limits 是一个类模板,您可以将任何数字类型传递给它,以获得它们可以容纳的最大值。
numeric_limits类模板有很多other information about numeric types as well。
【讨论】:
numeric_limits 是一个类模板。
numeric_limits 存在的原因,它在不同的实现中是不同的;-)
请参阅 limits.h (C) 或 climits (C++)。在这种情况下,您需要 INT_MAX 常量。
【讨论】:
我知道这是一个老问题,但也许有人可以使用这个解决方案:
int size = 0; // Fill all bits with zero (0)
size = ~size; // Negate all bits, thus all bits are set to one (1)
到目前为止,我们的结果是 -1,直到 size 是一个有符号整数。
size = (unsigned int)size >> 1; // Shift the bits of size one position to the right.
正如标准所说,如果变量是有符号且为负数,则移入的位为 1,如果变量为无符号或有符号且为正数,则为 0。
由于 size 是有符号和负数的,我们会将符号位移入 1,这没有多大帮助,因此我们强制转换为 unsigned int,强制移入 0,将符号位设置为 0,同时让所有其他位保持 1。
cout << size << endl; // Prints out size which is now set to maximum positive value.
我们也可以使用掩码和异或,但我们必须知道变量的确切位大小。通过在位前移位,我们不必随时知道 int 在机器或编译器上有多少位,也不需要包含额外的库。
【讨论】:
我知道答案已经给出,但我只想知道从前,我曾经这样做过
int max = (unsigned int)-1
它会给出相同的结果
std::numeric_limits<int>::max()
?
【讨论】:
(int)(unsigned int)-1 是 -1(嗯,实际上它是实现定义的,但通常是 -1),而 std::numeric_limits<int>::max() 是一个很大的正值 int。但是,(unsigned int)-1 始终等于 std::numeric_limits<unsigned int>::max()。
在带有 aCC 编译器的 Hp UX 上:
#include <iostream>
#include <limits>
using namespace std;
int main () {
if (sizeof(int)==sizeof(long)){
cout<<"sizeof int == sizeof long"<<endl;
} else {
cout<<"sizeof int != sizeof long"<<endl;
}
if (numeric_limits<int>::max()==numeric_limits<long>::max()){
cout<<"INT_MAX == lONG_MAX"<<endl;
} else {
cout<<"INT_MAX != LONG_MAX"<<endl;
}
cout << "Maximum value for int: " << numeric_limits<int>::max() << endl;
cout << "Maximum value for long: " << numeric_limits<long>::max() << endl;
return 0;
}
打印出来:
sizeof int == sizeof long
INT_MAX != LONG_MAX
我检查了 int 和 long 类型都是 4bytes。 manpage limits(5) 说 INT_MAX 和 LONG_MAX 都是 2147483647
http://nixdoc.net/man-pages/HP-UX/man5/limits.5.html
因此,结论 std::numeric_limits:: 不可移植。
【讨论】: