C語言常用轉(zhuǎn)換函數(shù)實現(xiàn)原理
編程時,經(jīng)常用到進(jìn)制轉(zhuǎn)換、字符轉(zhuǎn)換。比如軟件界面輸入的數(shù)字字符串,如何將字符串處理成數(shù)字呢?今天就和大家分享一下。01
字符串轉(zhuǎn)十六進(jìn)制
代碼實現(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?轉(zhuǎn)換為大寫字母
????????if?(s1?>?9)
????????????s1?-=?7;
????????s2?=?toupper(h2)?-?0x30;
????????if?(s2?>?9)
????????????s2?-=?7;
????????pbDest[i]?=?s1*16? ?s2;
????}
}
02
十六進(jìn)制轉(zhuǎn)字符串
代碼實現(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);
}
03
字符串轉(zhuǎn)十進(jìn)制
代碼實現(xiàn):第一種,如果帶負(fù)號 這個就是atoi函數(shù)的實現(xiàn):int?my_atoi(const?char?*str)
{
????int?value?=?0;
????int?flag?=?1;?//判斷符號
????while?(*str?==?'?')??//跳過字符串前面的空格
????{
????????str ;
????}
????if?(*str?==?'-')??//第一個字符若是‘-’,說明可能是負(fù)數(shù)
????{
????????flag?=?0;
????????str ;
????}
????else?if?(*str?==?' ')?//第一個字符若是‘ ’,說明可能是正數(shù)
????{
????????flag?=?1;
????????str ;
????}//第一個字符若不是‘ ’‘-’也不是數(shù)字字符,直接返回0
????else?if?(*str?>=?'9'?||?*str?<=?'0')?
????{
????????return?0;????
????}
????//當(dāng)遇到非數(shù)字字符或遇到‘\0’時,結(jié)束轉(zhuǎn)化
????while?(*str?!=?'\0'?