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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14644716/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 18:33:02  来源:igfitidea点击:

How to output a character as an integer through cout?

c++iotype-conversioniostreamoutputstream

提问by xmllmx

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

我猜这是因为 cout 总是将 'char'、'signed char' 和 'unsigned char' 视为字符而不是 8 位整数。但是,“char”、“signed char”和“unsigned char”都是整型。

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

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

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

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

回答by daniel

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 *thiseither by value or by reference-to-const.

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

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?

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

回答by sheu

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

回答by Luka Pivk

Maybe this:

也许这个:

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

Hope it helps.

希望能帮助到你。

回答by omotto

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

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

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

I hope it helps.

我希望它有帮助。

回答by mt3d

What about:

关于什么:

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

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

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