如何安全地将数据从 unsigned char * 传输到 char *?

How can I transfer data from unsigned char * to char * safely?

我愿意将数据从 unsigned char hash[512 + 1] 安全地传输到 char res[512 + 1]

我的 C 哈希库 MHASH returns 一个结果,因此可以打印如下。

for (int i = 0; i < size /*hash block size*/; i++)
    printf("%.2x", hash[i]); // which is unsigned char - it prints normal hash characters in range [a-z,0-9]
printf("\n");

我愿意做那样的事情(见下文)。

const char* res = (const char *)hash; // "hash" to "res"
printf("%s\n", res); // print "res" (which is const char*) - if i do this, unknown characters are printed

我知道char和unsigned char的区别,但是不知道怎么传数据。任何答案将不胜感激,提前致谢。但请不要向我推荐 C++ (STD) 代码,我正在做一个与 STD 无关的项目。

鉴于 unsigned char 数组的内容是可打印字符,您始终可以安全地将其转换为 char。带有 memcpy 的硬拷贝或您已经编写的代码中的指针引用。

我猜这里的实际问题是 unsigned char 数组内容实际上不是可打印字符,而是某种格式的整数。您必须将它们从整数转换为 ASCII 字母。如何做到这一点取决于数据的格式,这在你的问题中并不清楚。

假设如下:

#define ARR_SIZE (512 + 1)

unsigned char hash[ARR_SIZE];
char res[ARR_SIZE];

/* filling up hash here. */

就这样:

#include <string.h>

...

memcpy(res, hash, ARR_SIZE);

好吧,谢谢你们的回答,但不幸的是还没有任何效果。我现在坚持使用下面的代码。

char res[(sizeof(hash) * 2) + 1] = { '[=10=]' };
char * pPtr = res;
for (int i = 0; i < hashBlockSize; i++)
    sprintf(pPtr + (i * 2), "%.2x", hash[i]);

return (const char *)pPtr;

直到有任何其他更高效的方法来完成这项工作。没错,我的问题跟MHASH库有很大关系。