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

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

    That particular implementation seems to store multi-character constants in little-endian format. In the constant 'ab' the character 'b' is the least significant byte (the little end) and the character 'a' is the most significant byte. If you viewed chars as an array, it'd be chars[0] = 'b' and chars[1] = 'a', and thus would be treated by printf as "ba".

    Also, I'm not sure how accurate you consider Wikipedia, but regarding C syntax it has this section:

    Multi-character constants (e.g. 'xy') are valid, although rarely useful — they let one store several characters in an integer (e.g. 4 ASCII characters can fit in a 32-bit integer, 8 in a 64-bit one). Since the order in which the characters are packed into one int is not specified, portable use of multi-character constants is difficult.

    So it appears the 'ab' multi-character constant format should be avoided in general.

提交回复
热议问题