我是ac编码器,是c ++的新手.
我尝试用奇怪的输出cout打印以下内容.对此行为的任何评论表示赞赏.
#include<iostream>
using namespace std;
int main()
{
unsigned char x = 0xff;
cout << "Value of x " << hex<<x<<" hexadecimal"<<endl;
printf(" Value of x %x by printf", x);
}
Run Code Online (Sandbox Code Playgroud)
输出:
Value of x ÿ hexadecimal
Value of x ff by printf
Run Code Online (Sandbox Code Playgroud)
Tha*_*tos 22
<<处理char您想要输出的"字符",并且只输出该字节.该hex只适用于类似于整数类型,所以下面会做你所期望的:
cout << "Value of x " << hex << int(x) << " hexadecimal" << endl;
Run Code Online (Sandbox Code Playgroud)
Billy ONeal的建议static_cast看起来像这样:
cout << "Value of x " << hex << static_cast<int>(x) << " hexadecimal" << endl;
Run Code Online (Sandbox Code Playgroud)
您正确地执行了十六进制部分,但 x 是一个字符,而 C++ 试图将其打印为一个字符。您必须将其强制转换为整数。
#include<iostream>
using namespace std;
int main()
{
unsigned char x = 0xff;
cout << "Value of x " << hex<<static_cast<int>(x)<<" hexadecimal"<<endl;
printf(" Value of x %x by printf", x);
}
Run Code Online (Sandbox Code Playgroud)