#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+()
来简单地按值或按返回 *this
对常量的引用。
关于c++ - 如何通过cout将字符输出为整数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14644716/