search

Home  >  Q&A  >  body text

c++ - CSAPP打印程序对象的字节表示问题?

CSAPP中有一段打印对象的字节表示的代码,代码如下:

typedef unsigned char * byte_pointer;
void show_bytes(byte_pointer start, int len) {
    int i;
    for (i = 0; i < len; i++)
        printf("%.2x ", start[i]);
    printf("\n");
}

int main()
{
    int x = 12345;
    show_bytes((byte_pointer) &x, sizeof(int));
}

请问这段代码中,强制转化发生了什么过程,为什么能够得到对象的字节表示?

PHP中文网PHP中文网2805 days ago636

reply all(1)I'll reply

  • PHPz

    PHPz2017-04-17 14:37:01

    x is an int value, which generally occupies 4 bytes. In the memory layout, you can think of this value as a byte array of length 4. For example, x=12345, which is 0x3039. In the memory layout, the layout of Data can be considered as start[0] as 0x00 and start[2] as 0x30. Of course, depending on the CPU endianness, the byte order will be reversed.

    reply
    0
  • Cancelreply