在C编程方式检测字节顺序++程序 [英] Detecting endianness programmatically in a C++ program

查看:216
本文介绍了在C编程方式检测字节顺序++程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有一种编程方式来检测你是否是一个大端或小端架构?我需要能够写入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.

这篇关于在C编程方式检测字节顺序++程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆