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_t
用uint8_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
来回逐字节复制.