编辑代码

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

// 将十六进制字符转换为对应的数值
unsigned char hexToByte(char hex) {
    if (hex >= '0' && hex <= '9') {
        return hex - '0';
    } else if (hex >= 'A' && hex <= 'F') {
        return hex - 'A' + 10;
    } else if (hex >= 'a' && hex <= 'f') {
        return hex - 'a' + 10;
    }
    return 0; // 处理错误情况(这里简单返回0)
}

// 函数将字符串转换为字节数组
unsigned char* convertStringToBytes(char *input, int *byteCount) {
    int len = strlen(input);
    if (len % 2!= 0) {
        // 输入字符串长度必须是偶数
        *byteCount = 0;
        return NULL;
    }
    *byteCount = len / 2;
    unsigned char *output = (unsigned char *)malloc(*byteCount * sizeof(unsigned char));
    if (output == NULL) {
        // 内存分配失败
        *byteCount = 0;
        return NULL;
    }
    int j = 0;
    for (int i = 0; i < len; i += 2) {
        output[j] = (hexToByte(input[i]) << 4) | hexToByte(input[i + 1]);
        j++;
    }
    return output;
}

int main() {
    char inputString[] = "14A21A25637E";
    int byteCount;
    unsigned char *bytes = convertStringToBytes(inputString, &byteCount);
    if (bytes!= NULL) {
        for (int i = 0; i < byteCount; i++) {
            printf("0x%02x ", bytes[i]);
        }
        free(bytes);
    }
    return 0;
}