I have a problem which I do not understand. I add characters to a standard string. Whe I take them out the value printed is not what I expected.
int main (int argc, char *argv[])
{
string x;
unsigned char y = 0x89, z = 0x76;
x += y;
x += z;
cout << hex << (int) x[0] << " " <<(int) x[1]<< endl;
}
The output:
ffffff89 76
What I expected:
89 76
Any ideas as what is happening here?
And how do I fix it?
You have to account for the fact that
charmay be signed. If you promote it tointdirectly, the signed value will be preserved. Rather, you first have to convert it to the unsigned type of the same width (i.e.unsigned char) to get the desired value, and then promote that value to an integer type to get the correct formatted printing.Putting it all together, you want something like this:
Or, using the C++-style cast: