C语言_数组间的字符串和十六进制的相互转换方式

网上有很多相关例程,但是都多少有点小错误,这个是我验证过没问题的。用于单片机和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);
}
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值