大端 小端

#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;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值