1

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 Answers1

3

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]) << " ";
Mark Ransom
  • 299,747
  • 42
  • 398
  • 622