#include<stdio.h>
#include<stdlib.h>
#define BYTE unsigned char
#define WORD unsigned short
union{// 利用union能提供数据多个视角的特性来验证
struct{
BYTE bll:4,blr:4,bh;
}byte;
struct{
WORD w;
}word;
}big_small_endian;
int main()
{
big_small_endian.byte.bll = 0x1;
big_small_endian.byte.blr = 0x2;
big_small_endian.byte.bh = 0x34;
printf("%hx\n",big_small_endian.word.w);
big_small_endian.word.w = 0x1234;
printf("%hx\n",big_small_endian.byte.bll);
printf("%hx\n",big_small_endian.byte.blr);
printf("%hx\n",big_small_endian.byte.bh);
return 0;
}
字节的顺序与不同的处理器架构特性有关,其中先存储最左边的字节为大端,先存储最右边的字节为为小端。
0x12
0x34
在大端为 0x1234,在小端为 0x3412.下面是验证的代码(我的机器处理器是Intel Pentium,为小端)
huangkq@huangkq-Lenovo-G450:~/Desktop/Algorithms$ gcc big_small_endian.c -o big_small_endian
huangkq@huangkq-Lenovo-G450:~/Desktop/Algorithms$ ./big_small_endian
3412
小端输出为3412.大端则为1234.
另外TCP/IP网络协议采用大端字节序,而htonl,htons,ntohs,ntohl这四个函数用于处理处理器与网络字节序的转换。包含在<arpa/inet.h>头文件中。
#include<stdio.h>
#include<stdlib.h>
#define BYTE unsigned char
#define WORD unsigned short
union{// 利用union能提供数据多个视角的特性来验证
struct{
BYTE bl,bh;
}byte;
struct{
WORD w;
}word;
}big_small_endian;
int main()
{
big_small_endian.byte.bl = 0x12;
big_small_endian.byte.bh = 0x34;
printf("%hx\n",big_small_endian.word.w);
return 0;
}