十六进制字符串转ASCII字符串-缩

#include <stdio.h>

// 函数将十六进制字符转换为对应的整数值
int hexCharToInt(char c) {
    if (c >= '0' && c <= '9') {
        return c - '0';
    } else if (c >= 'A' && c <= 'F') {
        return c - 'A' + 10;
    } else if (c >= 'a' && c <= 'f') {
        return c - 'a' + 10;
    }
    return -1; // 非法字符
}

// 函数将十六进制字符串转换为ASCII字符串(在同一个数组中)
void hexStringToAsciiInPlace(char* hexString) {
    int len = 0;

    for (int i = 0; hexString[i] && hexString[i + 1]; i += 2) {
        int highNibble = hexCharToInt(hexString[i]);
        int lowNibble = hexCharToInt(hexString[i + 1]);

        if (highNibble == -1 || lowNibble == -1) {
            printf("Error: 输入的十六进制字符串包含非法字符\n");
            return;
        }

        hexString[len++] = (char)((highNibble << 4) | lowNibble);
    }

    hexString[len] = '\0'; // 在原始数组上进行修改
}

int main() {
    char hexString[] = "31323334616263"; // 16进制字符串,存储在同一个数组中

    hexStringToAsciiInPlace(hexString);

    printf("转换后的字符串: %s\n", hexString);

    return 0;
}