C通用函數(shù):ASCII與十六制字符串互相轉(zhuǎn)換Andrew Huang <bluedrum@163.com> 轉(zhuǎn)載請注明作者及聯(lián)絡方式 在用QT做一個串口通訊軟件。在接收數(shù)據(jù)時,一般的串口收發(fā)軟件的數(shù)據(jù)窗口都有ASCII顯示模式,也可以轉(zhuǎn)換成HEX十六進制模式。這樣有利調(diào)試。 因
此寫了兩個函數(shù)進行轉(zhuǎn)換,其中ASCII轉(zhuǎn)16進制算法非常簡單,只是簡單轉(zhuǎn)換一下即可。 但是16進制轉(zhuǎn)ASCII碼的算法較難一點。
一是有可能用戶誤輸入破壞數(shù)據(jù)合法性,另外為美觀二個進制數(shù)之間用空格隔開。但是空格有時會被刪除,或者空格會被多加。這些情況在轉(zhuǎn)換時都需要考慮了。 在實際項目測試比較滿意,在界面切換界面不錯. 注意這里用了C的一個特殊語法:內(nèi)嵌函數(shù),str2bin(),它的特點是直接可以引用其父函數(shù)所有局部變量,這樣的可以大大減少函數(shù)參數(shù)的。
- //16進制ASCII字符串轉(zhuǎn)對應的二進制BUFFER.
-
//每個BYTE之間可以有空格
-
// 合法字符串:
-
// ab 00 DE ==>> AB 00 DE
-
// Ab00 DE ==>> AB 00 DE
-
// d 0 DEa ==> 0D 00 DE 0A
-
- //Author Andrew Huang <bluedrum@163.com>
-
//十六制字符串轉(zhuǎn)ASCII字符串
-
int OS_HexStrToBuf(const char * hex_str,char * hex_buf,int buf_len)
-
{
-
char * p ;
-
int cnt=0;
-
char num[8];
-
int idx =0,pos = 0;
-
-
int str2bin(){
-
unsigned char ch;
-
num[pos] =0;
-
-
ch = (char )strtol(num,NULL,16);
-
//printf("pos=%d,idx %d,*p=%c,p-1=%c,offset %d,ch %02x num \"%s\"\n",pos,idx,*p,p[-1],cnt,hex_buf[idx-1],num);
-
-
-
hex_buf[idx++] = ch;
-
if(idx == buf_len)
-
return -1;
-
-
pos = 0;
-
-
return ch;
-
}
-
-
for(p= (char *)hex_str; *p==' ' ; p++){
-
cnt++ ;//濾掉開始空格
-
}
-
-
for(; *p!=0 ;p++)
-
{
-
//printf("cnt %d, *p %c\n",cnt,*p);
-
-
-
if(*p==' ')
-
{
-
if(p[-1] ==' ')
-
{//連續(xù)空格
-
pos = 0;
-
continue;
-
}
-
-
if(str2bin() == -1)
-
return -1;
-
-
continue;
-
-
}
-
else if(pos == 2)
-
{
-
if(str2bin() == -1)
-
return -1;
-
}
-
-
if(!isxdigit(*p))
-
return -2;
-
-
num[pos++] = *p;
-
//printf("set pos %d %c\n",pos-1,*p);
-
-
-
cnt++;
-
-
}
-
-
if(pos > 0 )
-
{
-
-
if(str2bin() == -1)
-
return -1;
-
}
-
-
-
//printf("return %d,pos %d\n",idx,pos);
-
-
return idx;
-
}
- //Author : Andrew Huang <bluedrum@163.com>
-
//ASCII字符串轉(zhuǎn)十六制字符串
-
int OS_StrToHexStr(const char * str,char * hex_str,int buf_len)
-
{
-
char * p ,* pstr = hex_str;
-
int size,len = buf_len;
-
for(p = (char *)str;*p!=0; p++)
-
{
-
size = snprintf(pstr,len," %02X",*p);
-
len-=size;
-
if(len <=0)
-
return -1;
-
-
pstr+=size;
-
}
-
-
*pstr = 0;
-
-
return buf_len-len;
-
}
|