C语言如何直接将长十六进制值写入malloc分配的指针指向的内存
十六进制值写入动态内存的实现方法
原代码报错原因
- 解引用
void*指针非法:void是无类型,编译器无法判断解引用后操作的内存长度,必须先强转成具体类型的指针再操作 - 整数常量溢出:C语言内置整数类型最大为64位(8字节),你给出的十六进制值长度为42个字符,对应21字节,远超内置类型的存储上限,无法作为合法整数常量使用
- 隐含字节序问题:就算用自定义大整数类型赋值,也会因为CPU的字节序问题,导致写入内存的字节顺序和你预期的字符串顺序相反,最终打印乱码
实现方案
这里提供两种符合你需求的实现,都可以直接把十六进制对应的原始字节写入内存,不会经过整数转换步骤:
方案1:硬编码字节写入(适合隐藏字符串场景)
直接把十六进制每两位转换为\x开头的C字符转义符,用memcpy直接拷贝到动态内存中,编译后不会暴露明文字符串,符合你做小惊喜的需求:
#include <stdio.h> #include <stdlib.h> #include <string.h> int main() { // 21字节原始数据+1字节字符串结束符,共需22字节 int buf_size = 22; char* surprise = (char*)malloc(buf_size); if (surprise == NULL) { perror("malloc failed"); return 1; } // 直接写入十六进制对应的原始字节 memcpy(surprise, "\x77\x72\x69\x74\x69\x6e\x67\x20\x68\x65\x78\x20\x74\x6f\x20\x6d\x65\x6d\x6f\x72\x79", buf_size - 1 ); surprise[buf_size - 1] = '\0'; printf("%s\n", surprise); free(surprise); return 0; }
运行后会输出writing hex to memory。
方案2:通用十六进制转二进制函数(适合动态输入场景)
如果需要运行时动态转换任意十六进制字符串为字节,可以自己实现一个轻量转换函数:
#include <stdio.h> #include <stdlib.h> #include <string.h> // 单个十六进制字符转数值 static unsigned char hex_char_to_val(char c) { if (c >= '0' && c <= '9') return c - '0'; if (c >= 'a' && c <= 'f') return c - 'a' + 10; if (c >= 'A' && c <= 'F') return c - 'A' + 10; return 0; } /** * 十六进制字符串转二进制字节数组 * @param hex_str 输入的十六进制字符串,长度必须为偶数 * @param out_buf 输出的二进制缓存 * @param out_buf_size 输出缓存的容量 * @return 转换后的字节数,失败返回-1 */ int hex_to_bin(const char* hex_str, unsigned char* out_buf, int out_buf_size) { int hex_len = strlen(hex_str); int need_size = hex_len / 2; if (out_buf_size < need_size || hex_len % 2 != 0) { return -1; } for (int i = 0; i < need_size; i++) { out_buf[i] = (hex_char_to_val(hex_str[i * 2]) << 4) | hex_char_to_val(hex_str[i * 2 + 1]); } return need_size; } int main() { const char* target_hex = "77726974696E672068657820746F206D656D6F7279"; int bin_len = strlen(target_hex) / 2; char* surprise = (char*)malloc(bin_len + 1); if (surprise == NULL) { perror("malloc failed"); return 1; } hex_to_bin(target_hex, (unsigned char*)surprise, bin_len); surprise[bin_len] = '\0'; printf("%s\n", surprise); free(surprise); return 0; }
内容的提问来源于stack exchange,提问作者Enes Eren
相关产品推荐
相关产品推荐

