c - 测试大端

标签 c gcc endianness

<分区>

Possible Duplicate:
Little vs Big Endianess: How to interpret the test

有没有一种简单的方法可以使用 gcc 或任何在线编译器(如 ideone for big endian)来测试代码?我不想使用 qemu 或虚拟机

编辑

有人可以解释这段代码在使用大端的系统上的行为吗?

#include <stdio.h>
#include <string.h>
#include <stdint.h>

int main (void)
{
    int32_t i;
    unsigned char u[4] = {'a', 'b', 'c', 'd'};

    memcpy(&i, u, sizeof(u));
    printf("%d\n", i);
    memcpy(u, &i, sizeof(i));
    for (i = 0; i < 4; i++) {
        printf("%c", u[i]);
    }
    printf("\n");
    return 0;
}

最佳答案

作为程序?

#include <stdio.h>
#include <stdint.h>

int main(int argc, char** argv) {
    union {
       uint32_t word;
       uint8_t bytes[4];
    } test_struct;
    test_struct.word = 0x1;
    if (test_struct.bytes[0] != 0)
        printf("little-endian\n");
    else
        printf("big-endian\n");
    return 0;
}

在小端架构上,首先存储最低有效字节。在大端架构中,最重要的字节首先存储。所以通过覆盖 uint32_tuint8_t[4] ,我可以检查哪个字节先出现。请参阅:http://en.wikipedia.org/wiki/Big_endian

GCC 特别定义了 __BYTE_ORDER__宏作为扩展。您可以针对 __ORDER_BIG_ENDIAN__ 进行测试, __ORDER_LITTLE_ENDIAN__ , 和 __ORDER_PDP_ENDIAN__ (我不知道它存在!)——见http://gcc.gnu.org/onlinedocs/cpp/Common-Predefined-Macros.html

另见 http://en.wikipedia.org/wiki/Big_endian


至于以与您机器的 native 字节顺序不匹配的字节顺序运行代码,那么您将不得不在具有不同字节顺序的体系结构上编译和运行它。因此,您将需要交叉编译,并在模拟器或虚拟机上运行。


编辑:啊,我没看到第一个printf() .

第一个printf将打印“1633837924”,因为大端机器将解释 'a'字符作为 int 中最重要的字节。

第二个printf将只打印“abcd”,因为 u 的值已从 i 来回逐字节复制.

关于c - 测试大端,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14660587/

相关文章:

c - 低估一个非常小的 GNU makefile

c - 为什么以及如何知道 scanf ("%c") 何时在内存中存储额外的数据? [C]

c++ - GCC constexpr 允许添加,但不允许使用地址进行按位或

endianness - 混合二进制文件的字节序是否有性能依据?

java - 从文件中快速读取小端整数

java - 将 UUID 转换为 GUID,反之亦然

c - 如何在C中的Excel工作表中创建另一行

c - 即使在包含 <stdlib.h> 之后,'exit' 也会发出警告

c++ - 使用无符号 "negative"数字递减指针

c - 错误 : expected identifier or ‘(’ before ‘__extension__’