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

后端 未结 4 963
一向
一向 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:34

    The answer to your question can be found in your tags: Endianness. On a little endian machine the least significant byte is stored first. This is a convention and does not affect efficiency at all.

    Of course, this means that you cannot simply cast it to a character string, since the order of characters is wrong, because there are no significant bytes in a character string, but just a sequence.

    If you want to view the bytes within your variable, I suggest using a debugger that can read the actual bytes.

提交回复
热议问题