Convert 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 characters of value 255. After conversion in bytes, the pointer has a value of -1 instead of 255. How can I correctly convert this data?

EDIT

Well, they came up with it that I really do not need to convert, but only the order of the bits. thanks for the help

+6
source share
2 answers

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

Now, to explain what you are doing: a typical representation of signed numbers in modern processors are two add-ons for which -1 has the maximum displayed bitpattern (all), which is the same as 255 for ΓΉnsigned char . So the cast does exactly what you ask for: reinterpreting unsigned chars as (signed) chars .

However, I can’t tell you how to properly convert the data, since it depends on what you want to do with it. How you do this may be good for your purposes if it is not your only choice - change the data type.

+5
source

It works as it should. The char type has a size of 1 byte, which is 8 bits. If it is unsigned, all bits are used to store the value, which makes the maximum value that a char can contain 255 (2 8 = 256 different values, starting from 0).

In the case of signed char one bit is used to store the character instead of the value, which leaves you only 7 bits for the value, allowing you to store numbers from -128 to 127.

So, when you hold 255 in an unsigned char , all bits are interpreted as a value, so you have 255. If you convert it to signed char , the first bit starts to be treated as a sign bit, and the data in the variable starts to be interpreted as -1.

+2
source

Source: https://habr.com/ru/post/954047/


All Articles