如何通过cout将字符输出为整数? [英] How to output a character as an integer through cout?
问题描述
#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
b $ b
但是,我什么都没有。
Yet, I got nothing.
我猜这是因为cout总是把'char','signed char'和'unsigned char'字符而不是8位整数。但是,'char','signed char'和'unsigned char'都是整数类型。
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?
So my question is: How to output a character as an integer through cout?
PS:static_cast(...)很丑陋,需要更多的工作来修剪额外的位。
PS: static_cast(...) is ugly and needs more work to trim extra bits.
推荐答案
我知道这个问题是很老的,但无论如何...
I know this question is pretty old but anyway...
char a = 0xab;
cout << +a; // promotes x to a type printable as a number, regardless of type
类型为一元+运算符提供普通语义。如果您要定义一个表示数字的类,则要提供一个带有规范语义的一元+运算符,创建一个运算符+(),它通过value或者reference-to-const返回* this。
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.
来源: Parashift.com - 如何打印一个字符作为数字?如何打印一个char *,以便输出显示指针的数字值?
这篇关于如何通过cout将字符输出为整数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!