- 字节序
低 高
|————————————————————————|
内存左低右高
0x12345678 大端序: 0x12345678 高位存低地址,低位存高地址 也是肉眼序、网络序列 只要少数cpu是大端序 小端序: 0x78563412 高位存高地址,低位存低地址 x86 arm等主流cpu是小端序
intel x86_64上程序
uint64_t hton64(uint64_t host)
{
uint64_t ret = 0;
uint64_t high,low;
low = host & 0xFFFFFFFF;
high = (host >> 32) & 0xFFFFFFFF;
low = htonl(low);
high = htonl(high);
ret = low;
ret <<= 32;
ret |= high;
return ret;
}
int main(int argc, char ** argv)
{
int i;
uint64_t ulValue = 0x12345678aabbccdd;
unsigned char *puc = (unsigned char *)(&ulValue);
for(i = 0; i < 8; i++)
printf("%X ", *(puc + i));
printf("\n");
ulValue = hton64(ulValue);
for(i = 0; i < 8; i++)
printf("%X ", *(puc + i));
printf("\n");
return;
}
[root@localhost test]# gcc main_test.c
[root@localhost test]# ./a.out
DD CC BB AA 78 56 34 12
12 34 56 78 AA BB CC DD
[root@localhost test]#
2.字节对齐
struct memtest{
unsigned int uiV1;
unsigned short usV2;
unsigned int uiV3;
unsigned char ucV4;
};
void outMembuf(void * buf, unsigned int uiLen)
{
int i, count = 0;
printf("buf len:%u\n",uiLen);
for(i=0; i < uiLen; i++)
{
if (0 ==(count%16))
printf("0x");
printf("%02X", *(unsigned char *)(buf+i));
count++;
if (0 ==(count%8))
printf(" ");
if (0 ==(count%16))
printf("\n");
}
}
int main(int argc, char ** argv)
{
struct memtest stmem = {0};
stmem.uiV1 = 0x11223344;
stmem.usV2 = 0x5566;
stmem.uiV3 = 0x778899aa;
stmem.ucV4 = 0xbb;
outMembuf(&stmem,sizeof(struct memtest));
}
[root@localhost test]# ./a.out
buf len:16
0x4433221166550000 AA998877BB000000
|