嵌入式面試2(轉帖)

1> 如何判斷一個板子的cpu 是big-endian 還是 Little-endian的?

用c實現非常簡單,10行左右,就可以判斷了, 關鍵考察新人是否瞭解了什麼是endian ,big-endian與little-endian的區別在哪裏, 如果這些不清楚,就算c再強,也是憋不出來的。

2> 判斷了 endian 後, 如何進行轉換, 寫兩個函數。

如果說上面的那個, 可能不能正確的考察出新人的c水平,下面這個,可就可以顯示了。

尤其是寫一個宏, 來實現。 我覺得宏最能體現出一個人的水平了, 大家都知道一個功能強大的,但是寫法又

非常簡單的宏,是不好寫的。 尤其是注意類型轉換, 大擴號什麼的。 寫一個函數就容易多了。

實現起來,或者 用宏,或者 用函數的形式, 都可以, 最好都試一下。

主要看的就是宏的使用。

比如:

寫成函數的形式:

typedef unsigned int u32 ;

typedef unsigned short u16 ;

u16 bswap16(u16);

u32 bswap32(u32);

寫成宏的形式:

#define BSWAP_16(x)

....

#define BSWAP_32(x)

....

比如: 0x1234 變成: 0x3412

或者: 0x12345678 變成 : 0x78563412

---

在下面的回覆寫出來,就有點亂了, 乾脆在這裏鐵出來吧 ,格式比較好:

1》判斷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>如何進行轉換:

#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 = 0x123490;

      //u32 var_int = 0x1234567890;

      //關鍵是要能對錯誤進行處理,給一個0x123490 照樣能得出 0x9034的值,而且, 佔內存要小的

      printf("macro conversion:%#x\n",BSWAP_16(0x123490 ));//要能正確轉換

      printf("macro conversion:%#x\n", BSWAP_32(0x1234567890)); //要能正確轉換

    

      printf("-----------------\n");

    

      printf("function conversion:%#x\n",bswap16(0x123490));

      printf("function conversion:%#x\n", bswap32(0x1234567890));

    

    

      return 0;

}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章