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
How to output a character as an integer through cout?
提问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 *this
either by value or by reference-to-const.
只要该类型提供+
具有普通语义的一元运算符,这就会起作用。如果您正在定义一个表示数字的类,要提供具有规范语义的一元 + 运算符,请创建一个operator+()
仅*this
按值或按常量引用返回的类。
回答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.
我希望它有帮助。