本文介绍了字节序-为什么将char放回Int16打印?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下在XCode中编译并运行的C代码:

The following C code, compiled and run in XCode:

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

打印'ba',而不是'ab'。

prints 'ba', rather than 'ab'.

为什么?

推荐答案

该特定实现似乎以Little-endian格式存储多字符常量。在常量'ab'中,字符'b'是最低有效字节(末尾),而字符'a'是最高有效字节。如果您将 chars 作为数组查看,则将是 chars [0] ='b' chars [1] ='a',因此printf将其视为 ba

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:

因此,通常应该避免使用'ab'多字符常量格式。

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

这篇关于字节序-为什么将char放回Int16打印?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-18 04:11
查看更多