c - Endianness——为什么 chars 将 Int16 打印倒过来?

标签 c xcode char endianness

以下 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/

相关文章:

c++ - 将 cin 用于 char 数组

c - C 中位域结构的大小

c - 如何检查 C 中是否由完全相同的字符组成更多单词?

android - Flutter:如何打开 main.dart

ios - Swift:AVAudioPlayer 不播放,线程可能出现错误?

c++ - 如何在 C++ 中将类的实例与 char * 变量进行比较?

C - 将 char 或 int 转换为二进制字符串并附加到 char 数组

c - C 中的函数如何返回多个值?

c++ - 使用 Arduino IDE 编程是否适合商业产品?

iphone - 如何计算交叉轨道误差(GPS/核心位置)