10进制和16进制数转ASCII码
int hex2ascii(unsigned char *hex, int hex_len, char *text)
{
char buffer[20];
int cnt=0;
for(cnt = 0; cnt < hex_len; cnt++)
{
memset(buffer, 0, 20);
sprintf(buffer, "%02X", hex[cnt]);
strcat(text, buffer);
}
return hex_len;
}
int dec2ascii(unsigned char *dec, int dec_len, char *text)
{
char buffer[30];
int cnt=0;
for(cnt = 0; cnt < dec_len; cnt++)
{
memset(buffer, 0, 30);
sprintf(buffer, "%02d", dec[cnt]);
strcat(text, buffer);
}
return dec_len;
}
16进制Ascii转16进制数组
参考
int16_t AsciiStrToHexArray(uint8_t*dst,uint8_t*src)
{
uint8_t ch;
uint16_t index=0;
if(strlen(src) == NULL)
{
return -1;
}
if(strlen(src)%2 == 0)
{
for(index = 0;index < strlen(src);index++)
{
if((src[index]>='0')&&(src[index]<='9'))
{
ch = src[index]-0x30;
}
else if((src[index]>='A')&&(src[index]<='F'))
{
ch = src[index]-0x37;
}
else if((src[index]>='a')&&(src[index]<='f'))
{
ch = src[index]-0x57;
}else{
return -1;
}
if(index%2 != 0)
{
dst[index/2]=dst[index/2]|ch;
}else{
dst[index/2]=ch<<4;
}
}
return (index / 2);
}else{
for(index = 0;index < strlen(src);index++)
{
if((src[index]>='0')&&(src[index]<='9'))
{
ch = src[index]-0x30;
}
else if((src[index]>='A')&&(src[index]<='F'))
{
ch = src[index]-0x37;
}else if((src[index]>='a')&&(src[index]<='f'))
{
ch = src[index]-0x57;
}
else{
return -1;
}
if((index+1) == strlen(src))
{
dst[index/2] = ch;
}else{
if(index%2 != 0)
{
dst[index/2]=dst[index/2]|ch;
}else{
dst[index/2]=ch<<4;
}
}
}
return (index / 2+1);
}
}