關於cpu大小端中int或short的存放順序,以及大小端序到網絡序的轉換
測試如下:
#include <stdio.h>
#include <arpa/inet.h>
int main()
{
unsigned int a = 0x12345678;
unsigned int b;
unsigned char *c;
unsigned char *d;
b = ntohl(a);
c = (unsigned char *)&a;
d = (unsigned char *)&b;
printf("a = 0x%x, b = 0x%x\n", a, b);
printf("c0 = 0x%x, c1 = 0x%x, c2 = 0x%x, c3 = 0x%x\n", c[0],c[1],c[2],c[3]);
printf("d0 = 0x%x, d1 = 0x%x, d2 = 0x%x, d3 = 0x%x\n", d[0],d[1],d[2],d[3]);
return 0;
}
大端mips
a = 0x12345678, b = 0x12345678
c0 = 0x12, c1 = 0x34, c2 = 0x56, c3 =0x78
d0 = 0x12, d1 = 0x34, d2 = 0x56, d3 =0x78
由此,大端的高位在低地址,通過ntohl轉換爲網絡字節序時數據沒有變化
小端arm:
a = 0x12345678, b = 0x78563412
c0 = 0x78, c1 = 0x56, c2 = 0x34, c3 = 0x12
d0 = 0x12, d1 = 0x34, d2 = 0x56, d3 = 0x78
由此,小端的低位在高地址,通過ntohl轉換爲網絡字節序時數據高低變換
也就是說,大端的系統上ntoh相關函數是不作處理的
小端的系統htoh相關函數會將高低位變換