做過(guò)socket 一、字節(jié)序定義字節(jié)序,顧名思義字節(jié)的順序,再多說(shuō)兩句就是大于一個(gè)字節(jié)類型的數(shù)據(jù)在內(nèi)存中的存放順序。其實(shí)大部分人在實(shí)際的開(kāi)發(fā)中都很少會(huì)直接和字節(jié)序打交道。唯有在跨平臺(tái)以及網(wǎng)絡(luò)程序中字節(jié)序才是一個(gè)應(yīng)該被考慮的問(wèn)題。一次Sun SPARC 在所有的介紹字節(jié)序的文章中都會(huì)提到字節(jié)序分為兩類:Big-Endian a) Little-Endian b) Big-Endian c) 二、高/ ----------------------- 。。。。。。 | . . 棧頂 ----------------------- | | NULL ( /|\ ----------------------- 堆 ----------------------- 未初始化的數(shù)據(jù) ---------------------- ( 初始化的數(shù)據(jù) ----------------------- 正文段( ----------------------- 以上圖為例如果我們?cè)跅I戏峙湟粋€(gè)unsigned char buf[4] 棧底(高地址) ---------- buf[3] buf[2] buf[1] buf[0] ---------- 棧頂(低地址) 現(xiàn)在我們弄清了高低地址,接著我來(lái)弄清高/ 高低地址和高低字節(jié)都弄清了。我們?cè)賮?lái)回顧一下Big-Endian 以unsigned int value = 0x12345678 Big-Endian: 棧底(高地址) --------------- buf[3] (0x78) -- buf[2] (0x56) buf[1] (0x34) buf[0] (0x12) -- --------------- 棧頂(低地址) Little-Endian: 棧底(高地址) --------------- buf[3] (0x12) -- buf[2] (0x34) buf[1] (0x56) buf[0] (0x78) -- --------------- 棧頂(低地址) 在現(xiàn)有的平臺(tái)上Intel 三、網(wǎng)絡(luò)字節(jié)序的轉(zhuǎn)換假設(shè)對(duì)于little endian #include <stdio.h> struct ST{ short val1; short val2; }; union U{ int val; struct ST st; }; int main(void) { int a = 0; union U u1, u2; a = 0x12345678; u1.val = a; printf("u1.val is 0x%x\n", u1.val); printf("val1 is 0x%x\n", u1.st.val1); printf("val2 is 0x%x\n", u1.st.val2); printf("after first convert is: 0x%x\n", htonl(u1.val)); u2.st.val2 = htons(u1.st.val1); u2.st.val1 = htons(u1.st.val2); printf("after second convert is: 0x%x\n", u2.val); return 0; } 輸出結(jié)果: u1.val is 0x12345678 val1 is 0x5678 val2 is 0x1234 after first convert is: 0x78563412 after second convert is: 0x78563412 按照這種想法我們實(shí)現(xiàn)long long int 代碼如下: #include <stdio.h> struct ST{ int val1; int val2; }; union test { long long int val; struct ST st; }; int main(void) { long long int a; union test u1, u2; a = 0x7654321087654321LL; u1.val = a; u2.st.val2 = htonl(u1.st.val1); u2.st.val1 = htonl(u1.st.val2); printf("val1 is 0x%x\n", u2.st.val1); printf("val2 is 0x%x\n", u2.st.val2); printf("u1.val is : 0x%llx\n", u1.val); printf("after convert is : 0x%llx\n", u2.val); return 0; } 執(zhí)行結(jié)果: val1 is 0x10325476 val2 is 0x21436587 u1.val is : 0x7654321087654321 after convert is : 0x2143658710325476 另外注意long long int 想看數(shù)據(jù)在內(nèi)存中如何存儲(chǔ)的,就用gdb |
|
來(lái)自: 水底の小魚(yú) > 《MFC技術(shù)》