大端小端與網路位元組序

2021-08-19 22:25:50 字數 1909 閱讀 7773

在裘宗燕翻譯的《程式設計實踐》裡,這對術語並沒有翻譯為「大端」和小端,而是「高尾端」和「低尾端」,這就好理解了:如果把乙個數看成乙個字串,比如11223344看成"11223344",末尾是個'\0','11'到'44'個占用乙個儲存單元,那麼它的尾端很顯然是44,前面的高還是低就表示尾端放在高位址還是低位址,它在記憶體中的放法非常直觀,如下圖:

}網路位元組序位元組序大端位元組序(bigendian)

小端位元組序(littleendian)

主機位元組序

不同的主機有不同的位元組序,如x86為小端位元組序,motorola 6800為大端位元組序,arm位元組序是可配置的。

網路位元組序規定為大端位元組序

#include #include int main()
關於:htonl

[cpp] 

view plain

copy

#include 

uint32_t htonl(uint32_t hostlong);  

uint16_t htons(uint16_t hostshort);  

uint32_t ntohl(uint32_t netlong);  

uint16_t ntohs(uint16_t netshort); 

h是主機host,n是網路net,l是長整形long,s是短整形short,所以上面這些函式還是很好理解的

[cpp] 

view plain

copy

#include 

#include 

intmain()  

執行結果:

值得注意的是:

in_addr_in   inet_addr(const char *strptr);

inet_addr的引數是乙個:點分十進位制字串,返回的值為乙個32位的二進位制網路位元組序的ipv4位址,不然的話就是:inaddr_none

而返回值為:in_addr_t:ipv4,一般為uint32_t

所以也可以定義為:unsigned long

char * inet_ntoa(struct in_addr inaddr);

引數是乙個結構體,所以要呼叫必須先定義乙個結構體。

位元組序轉換函式

uint32_t htonl(uint32_t hostlong);

uint16_t htons(uint16_t hostshort);

uint32_t ntohl(uint32_t netlong);

uint16_t ntohs(uint16_t netshort);

說明:在上述的函式中,h代表host;n代表network s代表short;l代表long

位址轉換函式

#include

#include

int inet_aton(const char *cp, struct in_addr *inp);

in_addr_t inet_addr(const char *cp);

char *inet_ntoa(struct in_addr in);

大端 小端與網路位元組序

大端 big endian 小端 little endian 以及網路位元組序的概念在程式設計中經常會遇到,其中網路位元組序 network byte order 一般是指大端 big endian,對大部分網路傳輸協議而言 傳輸,大端小端的概念是面向多位元組資料型別的儲存方式定義的,小端就是低位在...

小端位元組序與大端位元組序

端模式分為 小端位元組序和大端位元組序,也就是位元組在記憶體中的順序。小端位元組序 低位元組存於記憶體低位址 高位元組存於記憶體高位址。如乙個long型資料0x12345678 0x0029f458 0x78 0x0029f459 0x56 0x0029f45a 0x34 0x0029f45b 0x...

小端位元組序與大端位元組序

端模式分為 小端位元組序和大端位元組序,也就是位元組在記憶體中的順序。0x0029f458 0x78 0x0029f459 0x56 0x0029f45a 0x34 0x0029f45b 0x12 在以上資料存放於記憶體中的表現形式中,0x0029f458 0x0029f459 0x0029f45a...