Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 

Yet, I got nothing.

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.

So my question is: How to output a character as an integer through cout?

PS: static_cast(...) is ugly and needs more work to trim extra bits.

like image 670
xmllmx Avatar asked Feb 01 '13 10:02

xmllmx


People also ask

How do I print a character number?

char a = 0xab; cout << +a; // promotes a to a type printable as a number, regardless of type. This works as long as the type provides a unary + operator with ordinary semantics.

Can you cout a char?

We can use cast type here, by casting into char we are able to get result in character format. We can use cout<<char(65) or cout<<char(var), that will print 'A'. (65 is the ASCII value of 'A'). Here, output will be A.

Can int be a character?

Yes, a char is an integral type in all the popular languages in which it appears. "Integral" means that its spectrum is discrete and the smallest difference between any two distinct values is 1 .

Can we assign integer value to character?

We can convert int to char in java using typecasting. To convert higher data type into lower, we need to perform typecasting. Here, the ASCII character of integer value will be stored in the char variable. To get the actual value in char variable, you can add '0' with int variable.


1 Answers

char a = 0xab; cout << +a; // promotes a to a type printable as a number, regardless of type. 

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.

source: 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?

like image 82
daniel Avatar answered Oct 15 '22 20:10

daniel