以下 C 代码,在 XCode 中编译并运行:
UInt16 chars = 'ab';
printf("\nchars: %2.2s", (char*)&chars);
打印'ba',而不是'ab'。
为什么?
最佳答案
该特定实现似乎以小端格式存储多字符常量。在常量 'ab'
中,字符 'b'
是最低有效字节(小端),字符 'a'
是最重要的字节。如果您将 chars
视为一个数组,它将是 chars[0] = 'b'
和 chars[1] = 'a'
,因此将被 printf 视为 "ba"
。
此外,我不确定您认为维基百科有多准确,但关于 C syntax它有这个部分:
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.
因此看来'ab'
多字符常量格式通常应该避免。
关于c - Endianness——为什么 chars 将 Int16 打印倒过来?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7849574/