16进制数组转字符串

来源:互联网 发布:macbook下载软件工具 编辑:程序博客网 时间:2024/06/16 18:51

修改函数原型,确保每次malloc后可以释放堆控件

char * HexToString(char *str,unsigned char Hex[],unsigned char lenth){    unsigned char i=0,j=0;    unsigned char tema,temp;    //char *str=(char*)malloc(lenth*2);    for(i=0;i<lenth;i++)    {        tema=(Hex[i]>>4)&0x0F;        str[j]=IntToStr(tema);        j++;        temp=Hex[i]&0x0F;        str[j]=IntToStr(temp);        j++;    }    str[j]='\0';    return str;}
<pre name="code" class="cpp">char *strH=(char*)malloc(4*2);   QByteArray macStr=HexToString(strH,addrC,4);   if(strH!=NULL)free(strH);





今天做东西要用这个,读出来的ID号是16进制的,但是返回给上层的是字符串,LINUX下的底层函数想不到。比如unsigned char temp[10]={0xAB,0XAB,0XAB,0XAB,0XDB,0XEB,0XAB,0XAC,0XAC,0xee};我要输出的就是这样子,底层传上来的不是ASCII码。蛋痛得很`其他资料也没找到,本来想用sprintf函数的。可是完全不对头。后面已经写了这个功能函数。

# include <stdlib.h>#define DATA_LENGTH 20
//函 数 名:StrToInt()//功能描述:把字符转换成对应的数字,比如a转换成10char StrToInt(char aChar){    char ss;    switch(aChar)    {        case '0': ss= 0;break;        case '1': ss= 1;break;        case '2': ss= 2;break;        case '3': ss= 3;break;        case '4': ss= 4;break;        case '5': ss= 5;break;        case '6': ss= 6;break;        case '7': ss= 7;break;        case '8': ss= 8;break;        case '9': ss= 9;break;        case 'A': ss= 10;break;        case 'B': ss= 11;break;        case 'C': ss= 12;break;        case 'D': ss= 13;break;        case 'E': ss= 14;break;        case 'F': ss= 15;break;        default:break;    }    //printf("%c\n",ss);    return ss;}


//函 数 名:HexToAsc()//功能描述:把16进制转换为ASCIIchar IntToStr(unsigned char aChar){char ss;switch(aChar){case 0: ss= '0';break;case 1: ss= '1';break;case 2: ss= '2';break;case 3: ss= '3';break;case 4: ss= '4';break;case 5: ss= '5';break;case 6: ss= '6';break;case 7: ss= '7';break;case 8: ss= '8';break;case 9: ss= '9';break;case 10: ss= 'A';break;case 11: ss= 'B';break;case 12: ss= 'C';break;case 13: ss= 'D';break;case 14: ss= 'E';break;case 15: ss= 'F';break;default:break;}//printf("%c\n",ss);    return ss; } char * HexToString(unsigned char Hex[],unsigned char lenth){unsigned char i=0,j=0;unsigned char tema,temp;char *str=(char*)malloc(lenth*2);printf("Large:-----%d\n",lenth*2);for(i=0;i<lenth;i++){tema=(Hex[i]>>4)&0x0F;printf("%d\n",tema);str[j]=IntToStr(tema);printf("i=%d, %c\n",i,str[j]);j++;temp=Hex[i]&0x0F;printf("%d\n",temp);str[j]=IntToStr(temp);printf("i=%d, %c\n",i,str[j]);j++;}str[j]='\0';printf("Large:--j=%d\n",j);for(i=0;i<lenth*2;i++){printf("kkkkk:i=%d  ;str[i]:%c\n",i,str[i]);}printf("wqf:%s\n",str);return str;}void main(){char *str=NULL;unsigned char temp[10]={0xAB,0XAB,0XAB,0XAB,0XDB,0XEB,0XAB,0XAC,0XAC,0xee};str=HexToString(temp,10);printf("%s\n",str);}