How to output a character as an integer through cout?

只谈情不闲聊 提交于 2019-11-26 03:55:43

问题


#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.


回答1:


char a = 0xab;
cout << +a; // promotes a to a type printable as a number, regardless of type.

This works as long as the type provides a unary + operator with ordinary semantics. If you are defining a class that represents a number, to provide a unary + operator with canonical semantics, create an operator+() that simply returns *this either by value or by reference-to-const.

source: Parashift.com - How can I print a char as a number? How can I print a char* so the output shows the pointer's numeric value?




回答2:


Cast them to an integer type, (and bitmask appropriately!) i.e.:

#include <iostream>

using namespace std;

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

    cout << hex;
    cout << (static_cast<int>(c1) & 0xFF) << endl;
    cout << (static_cast<int>(c2) & 0xFF) << endl;
    cout << (static_cast<unsigned int>(c3) & 0xFF) << endl;
}



回答3:


Maybe this:

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

Hope it helps.




回答4:


Another way to do it is with std::hex apart from casting (int):

std::cout << std::hex << (int)myVar << std::endl;

I hope it helps.




回答5:


What about:

char c1 = 0xab;
std::cout << int{ c1 } << std::endl;

It's concise and safe, and produces the same machine code as other methods.



来源:https://stackoverflow.com/questions/14644716/how-to-output-a-character-as-an-integer-through-cout

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!