Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting unsigned char * to char *

here is my code:

std::vector<unsigned char> data;
... // put some data to data vector
char* bytes= reinterpret_cast<char*>(imageData.data());

My problem is that in vector 'data' I have chars of value 255. After conversion in bytes pointer I have values of -1 instead of 255. How should I convert this data properly?

EDIT

Ok, its come up that I really dont need conversion but only a bits order. THX for trying help

like image 982
AYMADA Avatar asked Sep 18 '13 09:09

AYMADA


1 Answers

char can be either signed or unsigned depending on the platform. If it is signed, like on your platform, it has a guaranteed range from -128 to 127 by the standard. For common platforms it is an 8bit type, so those are the only values that it can hold. This means that you can't represent 255 as a char.

Now to explain what you are seing: The typical representation of signed numbers in modern processors is two's-complement, for which -1 has the maximum representable bitpattern (all ones), which is the same as 255 for ùnsigned char. So the cast does exactly what you ask it to: reinterpreting the unsigned chars as (signed) chars.

However I can't tell you how to convert the data properly, since that depends on what you want to do with it. The way you are doing it might be fine for your purposes, if it isn't your only choice is to change the datatype.

like image 121
Grizzly Avatar answered Oct 17 '22 03:10

Grizzly