方法一:
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占用的字节数
- #include <iostream>
- using namespace std;
- #define my_sizeof(L_Value) (char* )(&L_Value + 1) - (char* )&L_Value
- int main()
- {
- int i;
- double f;
- double a[4];
- double* q;
- cout<<my_sizeof(i)<<endl;//4
- cout<<my_sizeof(f)<<endl;//8
- cout<<my_sizeof(a)<<endl;//32
- cout<<my_sizeof(q)<<endl;//4
- cout<<my_sizeof("aadf")<<endl;//5
- system("pause");
- return 0;
- }
(char* )&L_Value返回L_Value的地址的第一个字节,(char* )(&L_Value+1)返回L_Value的地址的下一个地址的第一个字节,所以他们之差为它所占字节数。
或者用如下方式
- #include <iostream.h>
- template <class Any>
- int LengofArray(Any* p)
- {
- return int(p+1) - int(p);
- }
- int main()
- {
- int* i;
- double* q;
- char a[10];
- cout<<LengofArray(i)<<endl;
- cout<<LengofArray(q)<<endl;
- cout<<LengofArray(&a)<<endl;
- return 0;
- }