Michael Blake
Michael Blake

Reputation: 995

Working with chars and only solution I've found is to static_cast twice. Is there a way around this?

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

Answers (1)

M.M
M.M

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

Related Questions