如何通过cout将字符输出为整数?

时间:2013-02-01 10:53:52

标签: c++ io type-conversion iostream outputstream

#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;
}

我预计输出如下:

ab
cd
ef

然而,我一无所获。

我想这是因为cout总是将'char','signed char'和'unsigned char'视为字符而不是8位整数。但是,'char','signed char'和'unsigned char'都是完整的类型。

所以我的问题是:如何通过cout将字符输出为整数?

PS:static_cast(...)很难看,需要更多工作来修剪额外的位。

6 个答案:

答案 0 :(得分:90)

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

只要该类型为普通语义提供一元+运算符,就可以正常工作。如果要定义一个表示数字的类,要为一元+运算符提供规范语义,请创建一个operator+(),它只是通过值或引用到const返回*this

来源: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?

答案 1 :(得分:9)

将它们转换为整数类型,(并适当地使用位掩码!),即:

#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;
}

答案 2 :(得分:6)

也许这个:

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

希望它有所帮助。

答案 3 :(得分:1)

另一种方法是重载 << 运算符:

#include <iostream>

using namespace std;
typedef basic_ostream<char, char_traits<char>> basicOstream;

/*inline*/ basicOstream &operator<<(basicOstream &stream, char c) {
    return stream.operator<<(+c);
}
/*inline*/ basicOstream &operator<<(basicOstream &stream, signed char c) {
    return stream.operator<<(+c);
}
/*inline*/ basicOstream &operator<<(basicOstream &stream, unsigned char c) {
    return stream.operator<<(+c);
}

int main() {
    char          var1 = 10;
    signed char   var2 = 11;
    unsigned char var3 = 12;
    
    cout << var1 << endl;
    cout << var2 << endl;
    cout << var3 << endl;
    
    return 0;
}

打印以下输出:

10
11
12

Process finished with exit code 0

我认为它非常简洁和有用。希望有用!


此外,如果您希望它打印 hex 值,您可以这样做:

basicOstream &operator<<(basicOstream &stream, char c) {
    return stream.operator<<(hex).operator<<(c);
} // and so on...

答案 4 :(得分:0)

另一种方法是使用 std :: hex ,除了 cast(int)

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

我希望它有所帮助。

答案 5 :(得分:0)

那又怎么样:

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

简洁,安全。