gpt4 book ai didi

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

转载 作者:IT老高 更新时间:2023-10-28 14:00:27 26 4
gpt4 key购买 nike

#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对常量的引用。

来源: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?

关于c++ - 如何通过cout将字符输出为整数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14644716/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com