如何用C++判断一个系统是16位、32位还是64位?
方法一:使用指针的sizeof()判断
#include <iostream>
using namespace std;
int main()
{
int *p = nullptr;
if(sizeof(p) == 8)
{
cout << "64 bits system" << endl;
}
else if(sizeof(p) == 4)
{
cout << "32 bits system" << endl;
}
else if(sizeof(p) == 2)
{
cout << "16 bits" <<endl;
}
else
{
cout << "unknown system" << endl;
}
return 0;
}
方法二:使用预定义宏来判断
#include <iostream>
using namespace std;
int main()
{
#ifdef __x86_64__
{
cout << "64 bits system" << endl;
}
#elif defined __x86_32__
{
cout << "32 bits system" << endl;
}
#elif defined __x86_16__
{
cout << "16 bits" <<endl;
}
#else
{
cout << "unknown system" << endl;
}
#endif
return 0;
}
方法三:使用整数溢出来判断(该方法可能有点小问题,同一个系统输出结果和其它2种不一致,原因暂未找到)
不同系统的基本数据类型的字节长度区别,如下表:
平台/类型 | char | short | int | long | long long |
---|---|---|---|---|---|
16位 | 1 | 2 | 2 | 4 | 8 |
32位 | 1 | 2 | 4 | 4 | 8 |
64位 | 1 | 2 | 4 | 8 | 8 |
#include <iostream>
using namespace std;
int main()
{
int test = (1 << 15);
if(test > 0)
{
int test_2 = (1 << 31);
if(test_2 > 0)
{
cout << "64 bits system" <<endl;
}
else
{
cout << "32 bits system" << endl;
}
}
else
{
cout << "16 bits system" << endl;
}
return 0;
}