主机字节序和网络字节序

主机字节序和网络字节序

小端模式:低序字节储存在起始地址的排序方式称为小端模式,

大端模式:高序字节储存在起始地址的排序方式称为大端模式。

主机字节序:大端和小端模式都有使用的系统,当前系统使用的字节序称为主机字节序

网络协议栈必须对网络上的字节序达成一致,保证数据的正常传输,因此网络上采用大端字节序来传递多字节整数。主机字节序和网络字节序之间的转换API如下所示:

#include <netinet/in.h>
uint16_t htons(uint16_t h);//host short --> net short
uint32_t htonl(uint32_t h);//host long --> net long
uint16_t ntohs(uint16_t n);//net short --> host short
uint32_t ntohl(uint32_t n);//net long --> host long

一个简单的判断主机字节序的代码:

#include <stdio.h>

int
main(int argc, char **argv)
{
	union {
		short s;
		char c[sizeof(short)];
	} un;
	
	un.s = 0x0102;

	if (sizeof(short) == 2) {
		if (un.c[0] == 1 && un.c[1] == 2) 
			printf("this is big-end system\n");
		if (un.c[0] == 2 && un.c[1] == 1)
			printf("this is small-end system\n");
		else
			printf("unknow byteorder system\n");
	}
    
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值