xml*_*lmx 52 c++ io iostream outputstream type-conversion
#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;
}
Run Code Online (Sandbox Code Playgroud)
我预计输出如下:
ab
cd
ef
Run Code Online (Sandbox Code Playgroud)
然而,我一无所获.
我想这是因为cout总是将'char','signed char'和'unsigned char'视为字符而不是8位整数.但是,'char','signed char'和'unsigned char'都是完整的类型.
所以我的问题是:如何通过cout将字符输出为整数?
PS:static_cast(...)很难看,需要更多的工作来修剪额外的比特.
小智 97
char a = 0xab;
cout << +a; // promotes a to a type printable as a number, regardless of type.
Run Code Online (Sandbox Code Playgroud)
只要该类型为+普通语义提供一元运算符,这就可以工作.如果要定义一个表示数字的类,要为一元+运算符提供规范语义,请创建一个operator+()只返回*this值或引用到const.
来源:Parashift.com - 如何将字符作为数字打印?如何打印char*以便输出显示指针的数值?
将它们转换为整数类型,(和bitmask适当!)即:
#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;
}
Run Code Online (Sandbox Code Playgroud)