Search code examples
objective-chashobjective-c++mhash

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


I am willing to transfer data from unsigned char hash[512 + 1] to char res[512 + 1] safely.

My C hashing library MHASH returns a result so it can be printed as listed below.

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");

I am willing to do something like that (see below).

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

I know the difference between char and unsigned char, but I don't know how to transfer data. Any answer would be greatly appreciated, thanks in advance. But please do not recommend me C++ (STD) code, I am working on a project that is not STD-linked.


Solution

  • Assuming the following:

    #define ARR_SIZE (512 + 1)
    
    unsigned char hash[ARR_SIZE];
    char res[ARR_SIZE];
    
    /* filling up hash here. */
    

    Just do:

    #include <string.h>
    
    ...
    
    memcpy(res, hash, ARR_SIZE);