0

I am trying to print these data type. But I get a very strange output instead of what I expect.

#include <iostream>

using namespace std;

int main(void)
{
    char data1 = 0x11;
    int data2 = 0XFFFFEEEE;
    char data3 = 0x22;
    short data4 = 0xABCD;   
    cout << data1 << endl;
    cout << data2 << endl;
    cout << data3 << endl;
    cout << data4 << endl;
}
Jan Schultke
  • 17,446
  • 6
  • 47
  • 96
Tom
  • 19
  • 2
  • 6
  • 4
    What output do you expect? Because I expect an invisible character, `-4370`, `"` and `-21555` (I assume that `int` is 32-bit and `short` is 16 bit and character enconding is ASCII-compliant) – Yksisarvinen Aug 18 '20 at 09:52
  • you have to "tell " your cout how to print that data if you want to print it in hex... – ΦXocę 웃 Пepeúpa ツ Aug 18 '20 at 09:52
  • Does this answer your question? [how do I print an unsigned char as hex in c++ using ostream?](https://stackoverflow.com/questions/673240/how-do-i-print-an-unsigned-char-as-hex-in-c-using-ostream) – Jan Schultke Aug 18 '20 at 10:15

1 Answers1

1

Most likely you expect data1 and data3 to be printed as some kind of numbers. However, the data type is character, which is why C++ (or C) would interpret them as characters, mapping 0x11 to the corresponding ASCII character (a control character), similar for 0x22 except some other character (see an ASCII table). If you want to print those characters as number, you need to convert them to int prior to printing them out like so (works for C and C++):

cout << (int)data1 << endl;

Or more C++ style would be:

cout << static_cast<int>(data1) << endl;

If you want to display the numbers in hexadecimal, you need to change the default output base using the hex IO manipulator. Afterwards all output is done in hexadecimal. If you want to switch back to decimal output, use dec. See cppreference.com for details.

cout << hex << static_cast<int>(data1) << endl;
Tom
  • 749
  • 4
  • 16
  • What's the point of your `(int)data1` version? You are printing to a `std::ostream` so that's not possible in C anyways. – Jan Schultke Aug 18 '20 at 21:59
  • There are many points: It's a legal way of writing it in C++. Some people still prefer the old-style C casts in certain situations (whether this makes sense is a different discussion). People who use C will be clever enough to figure out to use `printf` instead. – Tom Aug 20 '20 at 07:49