C++ 16进制转 ascii
时间: 2023-09-13 12:08:09 浏览: 109
可以使用以下代码将一个16进制字符串转换为对应的ASCII字符串:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main() {
char hex_string[] = "48656c6c6f20576f726c6421"; // 16进制字符串
int len = strlen(hex_string); // 获取字符串长度
char *ascii_string = malloc(len / 2 + 1); // 分配内存空间
int i, j;
for (i = 0, j = 0; i < len; i += 2, j++) {
int hex_digit_high = hex_string[i] >= 'a' ? hex_string[i] - 'a' + 10 : hex_string[i] - '0';
int hex_digit_low = hex_string[i + 1] >= 'a' ? hex_string[i + 1] - 'a' + 10 : hex_string[i + 1] - '0';
ascii_string[j] = (char)(hex_digit_high * 16 + hex_digit_low);
}
ascii_string[j] = '\0'; // 添加字符串结尾
printf("ASCII字符串:%s\n", ascii_string); // 打印结果
free(ascii_string); // 释放内存空间
return 0;
}
```
输出结果:
```
ASCII字符串:Hello World!
```