什么是大小端呢?
大端字节序存储:把一个数的低字节序的内容放在高地址处,相反,把高字节序的内容存放在低地址处,这种存储方式称为大端
小端字节序存储:把一个数的低字节序的内容存放在低地址处,把高字节序的内容存放在高地址处,这种存储方式称为小端
那么如何写一个程序来判断大小端呢,具体代码如下:
方法1:
判断当前机器的大小端存储
#include <stdio.h>
#include <stdlib.h>
int check_sys()
{
union
{
int i;
char c;
}un;
un.i = 1;
return un.c;
}
int main()
{
int ret = check_sys();
if (ret == 1)
{
printf("小端\n");
}
else
{
printf("大端\n");
}
return 0;
}
方法2:
#include <stdio.h>
#include <stdlib.h>
int check_sys()
{
int a = 1;
return *(char*)&a;//返回1表示小端,返回0表示大端
}
int main()
{
if (check_sys() == 1)
{
printf("小端\n");
}
else
{
printf("大端\n");
}
system("pause");
return 0;
}