【发布时间】:2023-03-08 17:25:01
【问题描述】:
我最近看到post 是关于 C 中的字节顺序宏的,但我无法真正理解第一个答案。
支持任意字节顺序的代码,可以放入文件中 调用 order32.h:
#ifndef ORDER32_H
#define ORDER32_H
#include <limits.h>
#include <stdint.h>
#if CHAR_BIT != 8
#error "unsupported char size"
#endif
enum
{
O32_LITTLE_ENDIAN = 0x03020100ul,
O32_BIG_ENDIAN = 0x00010203ul,
O32_PDP_ENDIAN = 0x01000302ul
};
static const union { unsigned char bytes[4]; uint32_t value; } o32_host_order =
{ { 0, 1, 2, 3 } };
#define O32_HOST_ORDER (o32_host_order.value)
#endif
您可以通过以下方式检查小端系统
O32_HOST_ORDER == O32_LITTLE_ENDIAN
我确实理解一般的字节顺序。这就是我对代码的理解:
- 创建小端、中端和大端的示例。
- 将测试用例与小端、中端和大端的示例进行比较,并确定主机的类型。
我不明白的是以下几个方面:
- 为什么需要联合来存储测试用例?
uint32_t不是保证能够根据需要保存 32 位/4 字节吗?分配{ { 0, 1, 2, 3 } }是什么意思?它将值分配给联合,但为什么 strange 标记带有两个大括号? - 为什么要检查
CHAR_BIT?一条评论提到检查UINT8_MAX会更有用吗?为什么char甚至在这里使用,但不能保证它是 8 位宽?为什么不直接使用uint8_t?我找到了指向 Google-Devs github 的 this 链接。他们不依赖此检查...有人可以详细说明吗?
【问题讨论】:
标签: c macros endianness