Alex Rivera | Logout

How to output a character as an integer through cout?

Asked 2013-02-01T10:53:51.650
83
#include <iostream>

using namespace std;

int main()
{  
    char          c1 = 0xab;
    signed char   c2 = 0xcd;
    unsigned char c3 = 0xef;

    cout << hex;
    cout << c1 << endl;
    cout << c2 << endl;
    cout << c3 << endl;
}

I expected the output are as follows:

ab
cd
ef

Yet, I got nothing.

I guess this is because cout always treats 'char', 'signed char', and 'unsigned char' as characters rather than 8-bit integers. However, 'char', 'signed char', and 'unsigned char' are all integral types.

So my question is: How to output a character as an integer through cout?

PS: static_cast(...) is ugly and needs more work to trim extra bits.

Edit
Report

1 Answer

7

Maybe this:

char c = 0xab;
std::cout << (int)c;

Hope it helps.

answered 2013-02-01T10:59:12.420

Your Answer