简体   繁体   中英

Strange output when printing char assigned to hex value using std::cout

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;
}

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM