您的位置:首页 > 编程语言 > C语言/C++

写个程序判断系统是多少位,是大端还是小端

2017-10-29 21:20 281 查看
一句话总结:位数用指针判断,大小端用union(联合体、共用体)。

#include <stdio.h>
int main()
{
int a = 0x12345678;
printf("Os is %ld\n", sizeof(int*));
printf("a's size is %ld\n", sizeof(a));
printf("int is %ld\n", sizeof(int));
printf("short is %ld\n", sizeof(short));
union ut
{
short s;
char c[2];
};
if(2 == sizeof(short))
{
ut u;
u.s = 0x0102;
if (0x01 ==u.c[0] && 0x02 == u.c[1])
printf("big endian\n");
else
printf("little endian\n");
}
return 0;
}

zjy@ubuntu:~$ vim test.cpp

zjy@ubuntu:~$ g++ -o test test.cpp (int大小32位,超过后提示overflow)

test.cpp: In function ‘int main()’:

test.cpp:4:10: warning:
overflow in implicit constant conversion [-Woverflow]

  int a = 0x1234567812345678;

          ^

zjy@ubuntu:~$ vim test.cpp

zjy@ubuntu:~$ g++ -o test test.cpp 

zjy@ubuntu:~$ ./test

Os is 8

a's size is 4

int is 4

short is 2

little endian

zjy@ubuntu:~$
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  C++