在實際工作中,字符串和其它數據類型的轉換是很常見的,庫函數有很多,比如 atoi , strtol ,sscanf 等,這些函數網上有很多資料,
我經常用到的就是十六進制的數值以字符串的形式傳輸,然後又要解析,這裡記錄一下我這邊的做法:
將2個字節的十六進制的字符串轉成short int 2個字節的整形數據:
short int xstrtoshortint(char *str)
{
//int len=strlen(str);
short int ivalue = 0; //這裡轉換為2個字節的整形數
if((len/2)>sizeof(ivalue))
{
printf(left overflow
);//會左溢出
}
int ioffset = 0; //移位
char *ptr; //字符指針
ptr = str; //從頭開始
while (*ptr != '') //到最後為字符串結束符
{
ivalue = ivalue << ioffset; //第一次不移位,之後每次左移4bit,十六進制一個字符代表4bit
if ((*ptr <= '9' && *ptr >= '0'))
{
ivalue = ivalue + (*ptr - '0');//ASCALL 碼相減
}
else if ((*ptr >= 'a' && *ptr <= 'f'))
{
ivalue = ivalue + (*ptr - 'a') + 10;
}
else if ((*ptr >= 'A' && *ptr <= 'F'))
{
ivalue = ivalue + (*ptr - 'A') + 10;
} // 給ivalue低位4bit 賦值
ptr++;
ioffset = 4;
}
return ivalue;
}
short int xstrtoshortint(char *str)
{
int len = strlen(str);
short int ivalue = 0;
for (int i = 0; i < len; i++)
{
if ((str[i] <= '9' && str[i] >= '0'))
{
ivalue = ivalue * 16 + (str[i] - '0'); //16進制 可換其它進制
}
else if ((str[i] >= 'a' && str[i] <= 'f'))
{
ivalue = ivalue * 16 + (str[i] - 'a') + 10;
}
else if ((str[i] >= 'A' && str[i] <= 'F'))
{
ivalue = ivalue * 16 + (str[i] - 'A') + 10;
}
}
return ivalue;
}
比如 調用xstrtoshortint(1A4e),可以得到一個 0x1A4e 的short int 數據, 如果要轉其它數據類型,原理相似!
轉字符串的話,sprintf函數是最常用的!