C语言 16进制数组 转 ASCII字符串函数

C语言 16进制数组 转 ASCII字符串函数
RET_SUCCESS、RET_FAILURE需自行定义
转换后的数组,其最后一个元素必须是’\0’,代表字符串结束

/**
 ****************************************************************************************
 * @brief	convert uint8_t array_a[n] to char array_b[2*n + 1]
 * @param[in] pHex: input array[], hex format
 * @param[out] pAscii: output array[], ascii format   
 * @param[in] hex_len: input array[]'s size
 * @note	if input_array[]'s size is n, the out_array[]'s size is 2n+1
 * @retval	RET_SUCCESS: operation success
			RET_FAILURE: operation failed
 ****************************************************************************************
 */
static int HexToAscii(uint8_t* pHex, char *pAscii, uint8_t hex_len)
{
    uint8_t hex_data[2] = {0x00};  
    for (uint16_t i = 0; i < hex_len; i++)
    {
        hex_data[0] = (pHex[i] & 0xF0) >> 4;
        hex_data[1] = pHex[i] & 0x0F;
        for (uint16_t j = 0; j < 2; j++)
        {
            //0-9 convert
            if(hex_data[j] < 10)
            {            
                hex_data[j] += 0x30; //0x30 is '0'
            }
            //A-F convert 
            else if(hex_data[j] < 16)
            {
                hex_data[j] = hex_data[j] - 10 + 0x41; //0x41 is 'A'                    
            }
            else
            {
                return RET_FAILURE;
            }
            *pAscii++ = hex_data[j];
        }               
    }
    return RET_SUCCESS;  
}
  • 4
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值