字节序:字节的排列顺序,指不同类型的cpu主机,内存存储“多字节整数”序列的方式,常用的方式是:大端字节序和小端字节序。
联合体:将不同的数据类型存储在同一片内空间,本题利用联合体的方式来判断大小端,定义一个联合体包含int类型和char类型,因为int型占4个字节,char类型占1个字节,先给int型一个数,在使用char类型返回该数在低地址的字节是哪个,从而判断计算机是小端还是大端。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
union BorS{
int a;
char b;
}bors;
int judgment(){
bors.a=0x87654321;
return bors.b;
}
int main(int argc, const char *argv[])
{
int c=judgment();
if(0x21==c){
printf("little endian\n");
}else if(0x87==c){
printf("big endian\n");
}
return 0;
}
输出结果为:little endian
即计算机为小端字节序