繁体   English   中英

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

[英]How to output a character as an integer through cout?

#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(...) 很丑,需要做更多的工作来修剪额外的位。

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

只要类型提供具有普通语义的一元+运算符,这就会起作用。 如果您正在定义一个表示数字的类,要提供具有规范语义的一元 + 运算符,请创建一个operator+() ,该operator+()仅通过值或通过引用对常量返回*this

来源: Parashift.com - 如何将字符打印为数字? 如何打印 char* 以便输出显示指针的数值?

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

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

也许这个:

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

希望能帮助到你。

关于什么:

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

它简洁而安全,并产生与其他方法相同的机器代码。

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

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

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

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

我希望它有帮助。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM