字节序——为什么字符会向后放入 Int16 打印? [英] Endianness -- why do chars put in an Int16 print backwards?

查看:44
本文介绍了字节序——为什么字符会向后放入 Int16 打印?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

The following C code, compiled and run in XCode:

UInt16 chars = 'ab';
printf("
chars: %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')是有效的,虽然很少有用——他们让一个整数存储多个字符(例如 4ASCII 字符可以放入一个 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.

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

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