c与c++比较
实现将十六进制字符串转换为字节数组
c实现 -
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
unsigned char* hexStringToByteArray(const char* hex_str, size_t* out_len) {
size_t len = strlen(hex_str);
size_t byte_count = 0;
// 计算实际的十六进制字符数(忽略空格)
for (size_t i = 0; i < len; ++i) {
if (isxdigit(hex_str[i])) {
++byte_count;
}
}
// 必须是偶数个十六进制字符
if (byte_count % 2 != 0) {
fprintf(stderr, "Invalid hex string: odd number of hex digits.\n");
*out_len = 0;
return NULL;
}
// 分配字节数组
*out_len = byte_count / 2;
unsigned char* byte_array = (unsigned char*)mal