确定编译时的字节序

问题描述 投票:58回答:10

是否有一种安全,可移植的方法来确定(在编译期间)要在其上编译程序的平台的字节顺序?我在用C写作。

[编辑]感谢您的回答,我决定坚持使用运行时解决方案!

c endianness
10个回答
32
投票

这是用于编译时检查


0
投票

使用CMake typedef union { uint32_t word; uint8_t bytes[4]; } byte_check; 作为

uint32_t word;
uint8_t * bytes = &word;

35
投票

要回答compile-time


16
投票

使用C99,您可以执行以下检查:


10
投票

#define I_AM_LITTLE (((union { unsigned x; unsigned char c; }){1}).c) 中读取的有趣内容:


7
投票

我想扩展为C ++提供C FAQ函数的答案


6
投票

不是在编译时,而是在运行时。这是我编写的用于确定字节序的C函数:


3
投票

来自sizeof(int)==4


1
投票

我曾经使用过这样的构造:


0
投票

据我所知,不是在编译期间。

在运行时,您可以进行一些琐碎的检查,例如将多字节值设置为已知的位字符串,并检查产生的字节数。例如,使用联合,

© www.soinside.com 2019 - 2024. All rights reserved.