Search code examples
c++pointerscharhexoctal

How does char* read this integer in hexadecimal? How is it working in ostream::write()?


#include <iostream>
using namespace std;

int main(){
    int x = 0x414243;
    cout.write( (char*)&x, 1);
    cout.write( ((char*)&x) + 1, 2);
}

The output is:

CBA

I don't understand what (char*)& is doing with x.

Looking at this ASCII table http://www.asciitable.com/, it seems to me write() is writing 141, 142, 143, in octal... in reverse!

How is char* managing to do this?


Solution

  • ASCII codes for upper case 'C', 'B', and 'A' are 67, 66, and 65, i.e. 0x43, 0x42, and 0x41.

    It looks like your computer is 32-bit little-endian, so the octets of 0x00414243 (two extra zeros are for clarity, to complete 32-bit int) are placed in memory as follows:

    0x43, 0x42, 0x41, 0x00
    

    This represents a null-terminated string "CBA".

    Note that on a big-endian hardware the octets would be placed in reverse order, i.e.

    0x00, 0x41, 0x42, 0x43
    

    so interpreting this number as a null-terminated string would produce empty output.