Endianness — why do chars put in an Int16 print backwards?

后端 未结 4 968
一向
一向 2021-01-25 05:17

The following C code, compiled and run in XCode:

UInt16 chars = \'ab\';
printf(\"\\nchars: %2.2s\", (char*)&chars);

prints \'ba\', rather t

4条回答
  •  北荒
    北荒 (楼主)
    2021-01-25 05:21

    It depends on the system you're compiling/running your program on.

    Obviously on your system, the short value is stored in memory as 0x6261 (ba): the little endian way.

    When you ask to decode a string, printf will read byte by byte the value you have stored in memory, which actually is 'b', then 'a'. Thus your result.

提交回复
热议问题