Why can't an unsigned char properly display a hex value [duplicate]

China☆狼群 提交于 2021-02-05 08:15:49

问题


I am trying to create an array of 1 byte values, using unsigned chars to hold the values.

my code looks like this:

unsigned char state[4][4] = {   {0xd4, 0xe0, 0xb8, 0x1e},
                                {0xbf, 0xb4, 0x41, 0x27},
                                {0x5d, 0x52, 0x11, 0x98},
                                {0x30, 0xae, 0xf1, 0xe5}};

Where each value is 2 hex digits which makes a byte. However, when I attempt to print the array out using

    cout << "\nInitial State \n------------------------------------------------------\n";
    for(int x = 0; x < 4; x++)
    {
        for(int y = 0; y < 4; y++)
            cout << hex << setw(2) << setfill('0') << state[x][y] << " ";
        cout << "\n";
    }

I don't get the hex value, but rather weird symbols

Initial State
---------------------
0Ô 0à 0¸ 0 
0¿ 0´ 0A 0' 
0] 0R 0 0˜ 
00 0® 0ñ 0å 

I understand the 0s come from set(w) and setfill('0') but I don't understand why it isn't showing the proper values. However, if I make the state an unsigned long, I then get the proper values.

So I'm confused. If a char holds exactly one byte, why can't the char display the byte as a hex value?


回答1:


cout is specialized to output the char type as a character, not a number. That goes for unsigned chars too. You get around it by casting to an unsigned int.

cout << hex << setw(2) << setfill('0') << static_cast<unsigned int>(state[x][y]) << " ";


来源:https://stackoverflow.com/questions/33764309/why-cant-an-unsigned-char-properly-display-a-hex-value

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!