可能重复:
小与大的耐力:如何解释测试
有没有一种简单的方法可以使用gcc或任何在线编译器(例如ideone for big endian)测试代码?我不想使用qemu或虚拟机
编辑
有人可以在使用big endian的系统上解释这段代码的行为吗?
#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;
}
Run Code Online (Sandbox Code Playgroud)
作为程序?
#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;
}
Run Code Online (Sandbox Code Playgroud)
在小端架构上,最不重要的字节首先存储。在大端架构上,最重要的字节首先存储。因此,通过将 auint32_t与 a重叠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
至于以与机器的本机字节序不匹配的字节序运行代码,那么你将不得不在具有不同字节序的架构上编译和运行它。因此,您将需要交叉编译,并在模拟器或虚拟机上运行。
编辑:啊,我没有看到第一个printf()。
第一个printf将打印“1633837924”,因为大端机器会将'a'字符解释为 int 中的最高有效字节。
第二个printf将只打印“abcd”,因为 的值u已从i.