big endian:大尾端,也称大端(高位)优先存储。
little endian:小尾端,也称小端(低位)优先存储。
如下00000000 00000000 00000000 00000001的存储
大尾端: 00000000 00000000 00000000 00000001
addr+0 addr+1 addr+2 addr+3 //先存高有效位(在低地址)
小尾端: 00000001 00000000 00000000 00000000
addr+0 addr+1 addr+2 addr+3 //先存低有效位(在低地址)
故要判断机器的体系结构是大尾端还是小尾端,以下程序可以完成任务:
|
大小尾端数据间的相互转换
/*
usage: to convert between the form of big-endian and little-endian
author: ydzhang
date: 2008年12月6日20:23:48
*/
#include <stdio.h>
typedef unsigned int u32;
typedef unsigned short u16;
#define BSWAP_16(x) \
(u16) ( ((((u16)(x) & 0x00ff)) << 8) \
| (((u16)(x) & 0xff00) >> 8) )
u16 bswap_16(u16 x)
{
return ((x & 0x00ff) << 8) | ((x & 0xff00) >> 8);
}
u32 bswap_32(u32 x)
{
return ((x & 0x000000ff) << 24) |
((x & 0x0000ff00) << 8) |
((x & 0x00ff0000) >> 8) |
((x & 0xff000000) >> 24);
}
int main()
{
u16 num_16 = 0x1234;
u32 num_32 = 0x12345678;
printf("%x\n", bswap_16(num_16));
printf("%x\n", BSWAP_16(num_16));
printf("%x\n", bswap_32(num_32));
return 0;
}
类别:C 查看评论