1

Please consider the following:

unsigned char a(65);
unsigned char z(90);

std::cout << std::hex << a << ", " << z <<std::endl;

Output:

A, Z

But desired output is:

41, 5a

To achieve this I'd like to avoid having to convert values like this, say:

std::cout << std::hex << int(a) << ", " << int(z) <<std::endl;

and instead have some magical manipulator that I can include beforehand:

std::cout << uchar_hex_manip << a << ", " << z << std::endl;

So my question is, how can I define 'uchar_hex_manip' to work as required?

UPDATE: I appreciate all the comments and suggestions so far but I have already said I want to avoid converting the values and no-one seems to have acknowledged that fully. The 'a << ", " << z' I mentioned above is representative of the values to be later streamed in - the actual use case of this in our application is that there is something more complex than that going on where for various reasons it is ideal not to have to shoe-horn in some casts for specific cases.

Benedict
  • 2,771
  • 20
  • 21
  • Don't think this kind of conversion gives much benefits – billz Jul 29 '13 at 10:01
  • 1
    You can write your own manipulator, that will return **your** class, derived from `basic_ostream`. In that class you could overwrite `operator<<` for `unsigned char` to print it as integers. Unfortunately, I have no time enough to write this as answer with examples now. *But note: only because this is possible **doesn't** mean you should do this; **I suggest cast to `int` instead**.* – awesoon Jul 29 '13 at 10:08
  • "want to avoid converting the values" --- not going to happen. "the actual use case of this in our application is that there is something more complex" --- then perhaps you are looking for a solution to a wrong problem. – n. m. could be an AI Jul 31 '13 at 12:00

1 Answers1

1

If you want to print char as hex, you will need to convert it to a an int:

 std::cout << std::hex << static_cast<int>('a'); 

should do the trick.

The reason std::hex doesn't work on char (or unsigned char) is that the stream output operator for char is defined to print the character as the output. There is no modifier to change this behaviour (and although @soon suggests to write your own class - that's a lot of work to avoid a cast).

Mats Petersson
  • 126,704
  • 14
  • 140
  • 227