嵌入式編程中一些常用的轉換函數(shù)
來自公眾號:嵌入式ARM
1、字符串轉十六進制
代碼實現(xiàn):
void?StrToHex(char?*pbDest,?char?*pbSrc,?int?nLen)
{
??char?h1,h2;
??char?s1,s2;
??int?i;
????for?(i=0;?i????{
????????h1?=?pbSrc[2*i];
????????h2?=?pbSrc[2*i 1];
????????s1?=?toupper(h1)?-?0x30;?//toupper?轉換為大寫字母
????????if?(s1?>?9)
????????????s1?-=?7;
????????s2?=?toupper(h2)?-?0x30;
????????if?(s2?>?9)
????????????s2?-=?7;
????????pbDest[i]?=?s1*16? ?s2;
????}
}
2、十六進制轉字符串
代碼實現(xiàn):
void?HexToStr(char?*pszDest,?char?*pbSrc,?int?nLen)
{
????char????ddl,?ddh;
????for?(int?i?=?0;?i?????{
????????ddh?=?48? ?pbSrc[i]?/?16;
????????ddl?=?48? ?pbSrc[i]?%?16;
????????if?(ddh?>?57)?ddh?=?ddh? ?7;
????????if?(ddl?>?57)?ddl?=?ddl? ?7;
????????pszDest[i?*?2]?=?ddh;
????????pszDest[i?*?2? ?1]?=?ddl;
????}
????pszDest[nLen?*?2]?=?'\0';
}
或者u16?Hex2StringArray?(u8?*pSrc,??u16?SrcLen,?u8?*pObj)
{
????u16?i=0;
????for(i=0;????i????{
????????sprintf((char?*)(pObj? ?i?*?2),?"X",?*(pSrc? ?i));
????}
????*(pObj? ?i?*?2)?=?'\0';
????return??(i?*?2);
}
效果:十六進制:0x13 0xAA 0x02轉為字符串:”13AAA2”
3、字符串轉十進制
代碼實現(xiàn):
第一種,如果帶負號 這個就是atoi函數(shù)的實現(xiàn):
int?my_atoi(const?char?*str)
{
????int?value?=?0;
????int?flag?=?1;?//判斷符號
????while?(*str?==?'?')??//跳過字符串前面的空格
????{
????????str ;
????}
????if?(*str?==?'-')??//第一個字符若是‘-’,說明可能是負數(shù)
????{
????????flag?=?0;
????????str ;
????}
????else?if?(*str?==?' ')?//第一個字符若是‘ ’,說明可能是正數(shù)
????{
????????flag?=?1;
????????str ;
????}//第一個字符若不是‘ ’‘-’也不是數(shù)字字符,直接返回0
????else?if?(*str?>=?'9'?||?*str?<=?'0')?
????{
????????return?0;????
????}
????//當遇到非數(shù)字字符或遇到‘\0’時,結束轉化
????while?(*str?!=?'\0'?