在C编程方式检测字节顺序++程序字节、顺序、方式、程序

2023-09-10 22:21:37 作者:一生的回眸只为你

有没有一种编程方式来检测你是否是一个大端或小端架构?我需要能够写入code,这将是英特尔或PPC系统上执行,并使用完全相同的code(即没有条件编译)。

Is there a programmatic way to detect whether or not you are on a big-endian or little-endian architecture? I need to be able to write code that will execute on an Intel or PPC system and use exactly the same code (i.e. no conditional compilation).

推荐答案

我不喜欢根据类型双关的方法 - 它通常会被编译器警告不要。这正是工会的!

I don't like the method based on type punning - it will often be warned against by compiler. That's exactly what unions are for !

int is_big_endian(void)
{
    union {
        uint32_t i;
        char c[4];
    } bint = {0x01020304};

    return bint.c[0] == 1; 
}

的原理是相当于类型情况下所建议的其他人,但是这是更明确的 - 并且根据C99,保证是正确的。海湾合作委员会prefers这比直接指针转换。

The principle is equivalent to the type case as suggested by others, but this is clearer - and according to C99, is guaranteed to be correct. gcc prefers this compared to the direct pointer cast.

这也比固定字节序在编译时好得多 - 用于OS支持多架构(在Mac OS X例如脂肪二进制),这将同时适用于PPC / i386的,而这是很容易惹事情并非如此。

This is also much better than fixing the endianness at compile time - for OS which support multi-architecture (fat binary on Mac os x for example), this will work for both ppc/i386, whereas it is very easy to mess things up otherwise.

 
精彩推荐
图片推荐