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;
}