字节序-为什么将char放回Int16打印? [英] Endianness -- why do chars put in an Int16 print backwards?

查看:102
本文介绍了字节序-为什么将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".

此外,我不确定您认为维基百科的准确性如何,但是关于 C语法它具有以下部分:

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


多字符常量(例如'xy')有效,尽管很少使用
很有用-他们让一个整数存储几个字符(例如4个
ASCII字符可以容纳32位整数,8个可以容纳64位整数)。
由于未将字符打包为一个int的顺序指定
,因此很难方便地使用多字符常量。

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'多字符常量格式。

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

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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆