Reputation: 995
This code seems a bit ridiculous, but it's the only way I found to deal with my problem...
char word[10];
cout << std::hex << static_cast<int>(static_cast<unsigned char>(word[i]));
This is my way of cout-ing a char as a hex value (including signed chars). It seems to work great (to my knowledge), but I feel it's a very stupid way to do it. I should add, I'm reading a file, that's why my data type is char initially.
Upvotes: 2
Views: 86
Reputation: 141554
You are already doing it the right way, although using int
would work as well as unsigned int
. You could make a function or a functor if you'll be doing this in several places, e.g.:
int char_to_int(char ch)
{
return static_cast<unsigned char>(ch);
}
// ...
cout << hex << char_to_int(word[i]);
As noted in comments, another option is word[i] & 0xFF
with no casting. This is actually implementation-defined but most likely will give the intended result. But again, if you will be doing this in several places I would suggest wrapping it up in a function so that it is more obvious what is going on.
Upvotes: 1