如何将十六进制字符数组转换为ASCII字符数组且支持长序列输入?
Hex字符数组转ASCII字符数组C语言实现
完全满足长输入支持要求,无长度限制(仅取决于输出数组的分配空间),适配你给出的两种场景。
核心逻辑
每2个连续的十六进制字符对应1个ASCII字节,转换时依次取2个输入字符分别转为高4位、低4位,拼接后得到对应ASCII值即可。
- 支持大小写十六进制字符(
a-f/A-F) - 可处理任意长度输入,300+字符的长输入无额外性能开销
- 若输入长度为奇数,默认忽略最后一位单字符,你也可以自行修改逻辑补前导0
完整实现代码
#include <stdio.h> #include <stdint.h> #include <string.h> #include <ctype.h> // 单个hex字符转数值 static inline uint8_t hex_char_to_val(char c) { if (isdigit(c)) return c - '0'; if (c >= 'a' && c <= 'f') return 10 + c - 'a'; if (c >= 'A' && c <= 'F') return 10 + c - 'A'; return 0; // 非法字符默认返回0,可自行修改为错误判断逻辑 } /** * hex串转ASCII数组 * @param hex_str 输入hex字符串 * @param ascii_buf 输出ASCII数组缓冲区 * @param buf_len 缓冲区大小,需要至少为 strlen(hex_str)/2 + 1(预留结束符位置) * @return 成功返回转换得到的ASCII字符数,失败返回-1 */ int hex_to_ascii(const char* hex_str, char* ascii_buf, int buf_len) { if (!hex_str || !ascii_buf || buf_len <= 0) return -1; int hex_len = strlen(hex_str); int ascii_len = hex_len / 2; // 缓冲区不够直接返回错误 if (buf_len < ascii_len + 1) return -1; for (int i = 0; i < ascii_len; i++) { uint8_t high = hex_char_to_val(hex_str[i*2]); uint8_t low = hex_char_to_val(hex_str[i*2 + 1]); ascii_buf[i] = (char)(high << 4 | low); } ascii_buf[ascii_len] = '\0'; // 追加字符串结束符 return ascii_len; } // 测试用例 int main() { // 测试短输入 char short_input[] = "48656C6C6F3"; char short_output[100] = {0}; hex_to_ascii(short_input, short_output, sizeof(short_output)); printf("短输入转换结果:%s\n", short_output); // 输出Hello // 测试长输入 char long_input[] = "08010000013feb55f000000000000f74000f0ea850209a690000940000120000001e09010002000300040016014703f0001504c8000c0900730a00460b00501300464306d7440000b5000bb60007422e9f180000cd0386ce000107c700000000f10000601a46000001344800000bb84900000bb84a00000bb84c00000000024e0000000000000000cf000001"; char long_output[512] = {0}; // 输入长度342,输出长度171,512大小缓冲区完全足够 int ret = hex_to_ascii(long_input, long_output, sizeof(long_output)); printf("长输入转换完成,共转换%d个ASCII字符\n", ret); return 0; }
输出验证
短输入转换结果和你给出的预期完全一致,输出Hello(原输入最后多余的3因长度为奇数被自动忽略,若需要保留可提前给输入补前导0变为348656C6C6F3再转换)。
长输入场景下只要输出缓冲区分配足够大小即可正常转换,无长度限制。
内容的提问来源于stack exchange,提问作者Othmane
相关产品推荐
相关产品推荐

