CPU的大小端问题
1> 如何判斷一個(gè)板子的cpu 是big-endian 還是 Little-endian的???? big-endian與little-endian
判斷endian :
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
?????? short int a = 0x1234;
?????? char *p = (char *)&a;
?????? printf("p=%#hhx/n",*p);
??????
?????? if(*p == 0x34)
?????????? printf("Little endian /n");
?????? else if(*p == 0x12)
?????????? printf("Big endian /n");
?????? else
?????????? printf("Unknow endian /n");??
?????? return 0;
}
2> little to big or big to little endian
#include <stdio.h>
#include <stdio.h>
typedef unsigned int u32;
typedef unsigned short u16;
#if 0
//simple: not check varible types
??????? #define BSWAP_16(x)???????? ( (((x) & 0x00ff) << 8 ) | (((x) & 0xff00) >> 8 )? )
//complex:check varible types
#else
??????? #define BSWAP_16(x)???????? (u16) ( ((((u16)(x)) & 0x00ff) << 8 ) | ((((u16)(x)) & 0xff00) >> 8 ) )
#endif
#define BSWAP_32(x)???? (u32) ( (( ((u32)(x)) & 0xff000000 ) >> 24) | (( ((u32)(x)) & 0x00ff0000 ) >> 8 ) |? / (( ((u32)(x)) & 0x0000ff00 ) << 8 ) | (( ((u32)(x)) & 0x000000ff ) << 24) )
u16 bswap16(u16 x)
{
?????? return (x & 0x00ff) << 8 | (x & 0xff00) >> 8? ;
}
u32 bswap32(u32 x)
{
?????? return?????? ( x & 0xff000000 ) >>24 | ( x & 0x00ff0000 ) >>8 | ( x & 0x0000ff00 ) <<8 |( x & 0x000000ff ) << 24? ;
}
int main(void)
{??????
????? u16 var_short = 0x1234;
????? u32 var_int = 0x1234567890;
????? printf("macro conversion:%#x/n",BSWAP_16(0x123490 ));???? //要能正確轉(zhuǎn)換
????? printf("macro conversion:%#x/n", BSWAP_32(0x1234567890)); //要能正確轉(zhuǎn)換
????? printf("-----------------/n");
?????
????? printf("function conversion:%#x/n",bswap16(0x123490));
????? printf("function conversion:%#x/n", bswap32(0x1234567890));?
????? return 0;
}
實(shí)現(xiàn)同樣的功能,我們來(lái)看看Linux 操作系統(tǒng)中相關(guān)的源代碼是怎么做的:
Linux 的內(nèi)核作者們僅僅用一個(gè)union 變量和一個(gè)簡(jiǎn)單的宏定義就實(shí)現(xiàn)了一大段代碼同樣的功能!由以上一段代碼我們可以深刻領(lǐng)會(huì)到Linux 源代碼的精妙之處!
(如果ENDIANNESS=’l’表示系統(tǒng)為little endian,為’b’表示big endian )。
其中關(guān)于printf()中"%#x"和"%hhx"請(qǐng)參考網(wǎng)址:(http://blog.csdn.net/striver1205/article/details/7477868)
總結(jié)
- 上一篇: 定义成员函数
- 下一篇: PIC中的#pragma idata 和