- 用共用体(联合体)的方式,判断本机的字节序?
#include<stdio.h>
typedef union
{
int a;
int b;
}_t;
int main(int argc, const char *argv[])
{
int a = 0x87654321;
char* ptr = (char*)&a;
printf("%d\n%#x\n",*ptr,*ptr);
if(*ptr == 0x21)
{
printf("小端\n");
}
else if(*ptr == 0x87)
{
printf("大端\n");
}
return 0;
}
2.字节序转换函数
//字节序转换函数
#include<stdio.h>
#include<arpa/inet.h>
int main(int argc, const char *argv[])
{
//htonl htons
unsigned int a = 0x87654321;
printf("%#x\n", a);
printf("%#x\n",htonl(a));
printf("%#x\n",htons(a));
putchar(10);
//ntohl ntohs
printf("%#x\n",ntohl(a));
printf("%#x\n",ntohs(a));
return 0;
}