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

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

问题描述

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

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 !

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

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

原理等同于其他人建议的类型案例,但这更清晰 - 根据 C99,保证是正确的.与直接指针转换相比,gcc 更喜欢这种方式.

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.

这也比在编译时修复字节序要好得多 - 对于支持多架构的操作系统(例如 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天全站免登陆