Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

cannot convert from 'unsigned char *' to 'char *' [duplicate]

Tags:

c++

char

unsigned

Possible Duplicate:
C++ style cast from unsigned char * to const char *

I have the unsigned char* digest; which is the output of a program and i would like to pass it to a char* S1;

I type char* S1=digest; and does not work

like image 847
Hashed Avatar asked Sep 10 '12 12:09

Hashed


People also ask

Can I cast unsigned char to char?

However, from i=128:255 the chars and the unsigned chars cannot be casted, or you would have different outputs, because unsigned char saves the values from [0:256] and char saves the values in the interval [-128:127]).

What is a unsigned char?

unsigned char is a character datatype where the variable consumes all the 8 bits of the memory and there is no sign bit (which is there in signed char). So it means that the range of unsigned char data type ranges from 0 to 255.


2 Answers

The simple answer: You need to cast it: reinterpret_cast<unsigned char*>(digest)

However, in this case you need to be aware that unsigned char* and char* are not really the same thing unless all elements in the array are less than 128.

char * either represents values from -128 to 127 (signed) or 0 to 255 (unsigned), the other always values from 0 to 255.

digest functions by their nature are likely to return values between 0 and 255, inclusive, in the result.

Also, the fact that the array might very well include null characters (the question does not really specify where the digest is coming from) many functions that accept char * or unsigned char* are likely to fail, since they assume the char* is a string (which it is not, really, if it is a binary digest of (presumably) fixed size)

like image 121
perh Avatar answered Nov 15 '22 02:11

perh


It's because unsigned char and char (which is really signed char in your compiler) are different. You have to make an explicit typecast:

char* S1 = reinterpret_cast<char*>(digest);
like image 45
Some programmer dude Avatar answered Nov 15 '22 02:11

Some programmer dude