可以在C++程序中编程检测字节序。

18 浏览
0 Comments

可以在C++程序中编程检测字节序。

有没有一种编程方式能够检测您的架构是大端还是小端? 我需要编写能够在Intel或PPC系统上执行并使用完全相同代码 (即没有条件编译)的代码。

admin 更改状态以发布 2023年5月24日
0
0 Comments

如果你有使用C++20编译器(如GCC 8+或Clang 7+),你就可以使用std::endian

注意:std::endian最初位于中,但在2019年科隆会议上被迁移到了中。GCC 8、Clang 7、8和9仍将其置于中,而GCC 9+和Clang 10+则将其放置于中。

#include 
if constexpr (std::endian::native == std::endian::big)
{
    // Big-endian system
}
else if constexpr (std::endian::native == std::endian::little)
{
    // Little-endian system
}
else
{
    // Something else
}

0
0 Comments

我不喜欢基于类型解析的方法-编译器通常会对其发出警告,这正是联合体的用途所在!

bool is_big_endian(void)
{
    union {
        uint32_t i;
        char c[4];
    } bint = {0x01020304};
    return bint.c[0] == 1;
}

这个原则与其他人建议的类型强制转换等价,但更为清晰,并且根据C99的规定,是保证正确的。GCC更喜欢这种方法,而不是直接指针转换。

这也比在编译时固定端序要好得多-对于支持多架构(例如Mac OS X上的fat binary)的操作系统,这将适用于ppc/i386,否则很容易搞砸。

0