Chinaunix

标题: 字节序 [打印本页]

作者: feiaix    时间: 2009-12-10 16:18
标题: 字节序
简而言之:
Big endian machine: It thinks the first byte it reads is the biggest.
Little endian machine: It thinks the first byte it reads is the littlest.
举个例子,从内存地址0x0000开始有以下数据
0x0000     0x12
0x0001     0x34
0x0002     0xab
0x0003     0xcd
如果我们去读取一个地址为0x0000的四个字节变量,若字节序为big-endian,则读出
结果为0x1234abcd;若字节序位little-endian,则读出结果为0xcdab3412.
如果我们将0x1234abcd写入到以0x0000开始的内存中,则结果为
                big-endian     little-endian
0x0000     0x12              0xcd
0x0001     0x23              0xab
0x0002     0xab              0x34
0x0003     0xcd              0x12
x86系列CPU都是little-endian的字节序.

所有网络协议也都是采用big endian的方式来传输数据的。所以有时我们也会把big endian方式称之为网络字节序。当两台采用不同字节序的主机通信时,在发送数据之前都必须经过字节序的转换成为网络字节序后再进行传输。

X86用 低地址空间存储数据的低位的。
这与Motorola的CPU是相反的。
现在网络上传输的数据的标准顺序为大端字节序。所以,X86就要进行转换。
转换非常简单:
#include  /* 用到的头文件 */
unsigned long htonl ( unsigned long hostlong );       /* 主机转网络 */
unsigned short htons ( unsigned short hostshort ); /* 主机转网络 */
unsigned long ntohl ( unsigned long netlong );        /* 网络转主机 */
unsigned short ntohs ( unsigned short netshort );   /*网络转主机 */



本文来自ChinaUnix博客,如果查看原文请点:http://blog.chinaunix.net/u/24855/showart_2116785.html




欢迎光临 Chinaunix (http://bbs.chinaunix.net/) Powered by Discuz! X3.2