用C++写个程序,如何判断一个操作系统是16位还是32位的?不能用sizeof()函数?(不用sizeof()函数求当前主机上的一个int占用几个字节)

本文介绍了两种检测系统位数的方法:通过特定数值的溢出表现判断系统位宽,并提供了一种不使用sizeof关键字确定变量大小的技术方案。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

方法一:

16位的系统下,

int i = 65536;

cout << i; // 输出0;//装不下,最高位溢出,剩下16位的当然是0;

int i = 65535;

cout << i; // 输出-1;//-1的补码是65535

而32位的系统下:

int i = 65536;

cout << i; // 输出65536;

int i = 65535;

cout << i; // 输出65535;

方法2:

int a = ~0;//按位取反运算,结果为(11111111111111111111111111111111)

if( a>65536 )

{

cout<<"32 bit"<<endl;

}

else

{

cout<<"16 bit"<<endl;

}

不用sizeof,求int占用的字节数

Cpp代码 
  1. #include <iostream>  
  2.   
  3.    
  4.   
  5. using namespace std;  
  6.   
  7.    
  8.   
  9. #define my_sizeof(L_Value)  (char* )(&L_Value + 1) - (char* )&L_Value  
  10.   
  11.    
  12.   
  13. int main()  
  14.   
  15.    
  16.   
  17. {  
  18.   
  19.     int i;  
  20.   
  21.     double f;  
  22.   
  23.     double a[4];  
  24.   
  25.     double* q;  
  26.   
  27.     cout<<my_sizeof(i)<<endl;//4  
  28.   
  29.     cout<<my_sizeof(f)<<endl;//8  
  30.   
  31.     cout<<my_sizeof(a)<<endl;//32  
  32.   
  33.     cout<<my_sizeof(q)<<endl;//4  
  34.   
  35.     cout<<my_sizeof("aadf")<<endl;//5  
  36.   
  37.     system("pause");  
  38.   
  39.     return 0;  
  40.   
  41. }  


(char* )&L_Value返回L_Value的地址的第一个字节,(char* )(&L_Value+1)返回L_Value的地址的下一个地址的第一个字节,所以他们之差为它所占字节数。

或者用如下方式

Cpp代码 
  1. #include <iostream.h>  
  2.   
  3. template <class Any>  
  4.   
  5. int LengofArray(Any* p)  
  6.   
  7. {  
  8.   
  9.     return int(p+1) - int(p);  
  10.   
  11. }  
  12.   
  13.    
  14.   
  15. int main()  
  16.   
  17. {  
  18.   
  19.     int* i;  
  20.   
  21.     double* q;  
  22.   
  23.     char a[10];  
  24.   
  25.     cout<<LengofArray(i)<<endl;  
  26.   
  27.     cout<<LengofArray(q)<<endl;  
  28.   
  29.     cout<<LengofArray(&a)<<endl;  
  30.   
  31.     return 0;  
  32.   
  33. }  
  34.    
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值