网上有很多相关例程,但是都多少有点小错误,这个是我验证过没问题的。用于单片机和stm32的,完美适配。
在这里插入代码片
char HexToChar(uint8_t hex)
{
char ch=0;
if(hex>0x0f)
return -1;
if((hex>=0)&&(hex<=0x09)) ch=hex+'0';
else if((hex>=0x0a)&&(hex<=0x0f)) ch=(hex&0x0f)+('a'-0x0a);
return ch;
}
void ArryToString(uint8_t *data,uint8_t data_len,uint8_t* string)
{
uint8_t * p_string=string;
for(uint8_t i=0;i<data_len;i++)
{
*(p_string++)=HexToChar(data[i]>>4);
*(p_string++)=HexToChar(data[i]&0x0f);
}
*p_string='\0';
}
int StringToHex(char *str, unsigned char *out, unsigned int *outlen)
{
char *p = str;
char high = 0, low = 0;
int tmplen = strlen(p), cnt = 0;
tmplen = strlen(p);
while(cnt < (tmplen / 2))
{
high = ((*p > '9') && ((*p <= 'F') || (*p <= 'f'))) ? *p - 48 - 7 : *p - 48;
low = (*(++ p) > '9' && ((*p <= 'F') || (*p <= 'f'))) ? *(p) - 48 - 7 : *(p) - 48;
out[cnt] = ((high & 0x0f) << 4 | (low & 0x0f));
p ++;
cnt ++;
}
if(tmplen % 2 != 0) out[cnt] = ((*p > '9') && ((*p <= 'F') || (*p <= 'f'))) ? *p - 48 - 7 : *p - 48;
if(outlen != NULL) *outlen = tmplen / 2 + tmplen % 2;
return tmplen / 2 + tmplen % 2;
}
int main()
{
char RxData2[100];
char RxData2_decrease[64];
u8 encode_Result[48] = { 0 }; //?????????
u8 encode_Result_1[64] = { 0 }; //?????????
ArryToString((uint8_t *)encode_Result,sizeof(encode_Result),(uint8_t *)encode_Result_1);
StringToHex(RxData2_decrease,RxData2_hex,RxData2_lenth);
}