模仿/模仿C中的大端行为?

我想知道是否有可能模仿一个大端行为,用于测试目的?

通过Windows或Linux,mingw或gcc。 这是一个代码示例,我希望仿真返回大端:

#include  #include  #include  #include  #if CHAR_BIT != 8 #error "Unsupported char size for detecting endianness" #endif int main (void) { short int word = 0x0001; char *byte = (char *) &word; if (byte[0]) printf("little endian"); else printf("big endian"); return 0; } 

您无法为测试目的切换endianes或类似的东西。 您可以做的是,为大端架构安装模拟器并为模拟器编译程序。 这是一种方式,在:

http://people.debian.org/~aurel32/qemu/

是各种QEMU支持的体系结构的Debian磁盘映像。 mips,sparc和arm是big-endian(不要下载任何以-el结尾的内容)。 我正在使用Debian Lenny进行MIPS( http://people.debian.org/~aurel32/qemu/mips/ )。 为您的平台安装QEMU,然后按照MIPS页面上的说明下载映像和内核文件。

现在,您可以从控制台启动到Debian 5 for MIPS。 登录到您的虚拟机,成为超级用户(密码为“root”)并安装C编译器:

 debian-mips:~# su - debian-mips:~# apt-get update debian-mips:~# apt-get install gcc 

启动编辑器并输入您的程序:

 debian-mips:~# pico foo.c debian-mips:~# gcc foo.c debian-mips:~# ./a.out big endian 

我想在我的小端英特尔机器上进行大端仿真,以测试与字节顺序相关的问题的程序。 QEMU PowerPC仿真器似乎是一个很好的解决方案。 我已经记录了下面设置它的步骤。

1)安装QEMU。

 nifty:~# aptitude update && aptitude install qemu 

2)从http://sourceforge.net/projects/mac-on-linux/files/下载Mac-on-Linux,并将下载中的’video.x’文件复制到’/ usr / share / qemu’。 这对于防止qemu-system-ppc抱怨它是必要的。

 nifty:~# tar -xjf mol-0.9.72.1.tar.bz2 nifty:~# cp mol-0.9.72.1/mollib/drivers/video.x /usr/share/qemu 

3)下载Debian for PowerPC并将其安装在QEMU硬盘映像上。

 susam@nifty:~/qemu$ wget --no-verbose http://cdimage.debian.org/debian-cd/5.0.4/powerpc/iso-cd/debian-504-powerpc-CD-1.iso 2010-06-19 02:55:06 URL:http://caesar.acc.umu.se/debian-cd/5.0.4/powerpc/iso-cd/debian-504-powerpc-CD-1.iso[675569664/675569664] -> "debian-504-powerpc-CD-1.iso" [1] susam@nifty:~/qemu$ qemu-img create powerpc.img 2G Formatting 'powerpc.img', fmt=raw size=2147483648 susam@nifty:~/qemu$ qemu-system-ppc -hda powerpc.img -cdrom debian-504-powerpc-CD-1.iso -boot d -m 512 

4)使用硬盘映像启动QEMU PowerPC仿真器。

 susam@nifty:~/qemu$ qemu-system-ppc -hda powerpc.img -m 512 

5)通过编写一个简单的C程序,validation我是在一个大端系统上。

 susam@lilliput:~$ cat endian.c #include  int main() { int n = 0x1; printf(*((char *) &n) ? "little-endian\n" : "big-endian\n"); return 0; } susam@lilliput:~$ gcc endian.c && ./a.out big-endian susam@lilliput:~$ 

如果你错过了双关语,Lilliputians原本是大人物。

您可以在所有不同用途之间抛出一堆hton *(Host TO Network)和ntoh *(Network TO Host)调用。 Network endian是Big Endian。

16位:htons =主机TO网络短ntohs =网络TO主机短路

32位:htonl =主机TO网络长ntohl =网络到主机长

实际上,主机到网络和网络到主机是相同的,因为相同的交换发生在任何一种方式。

它们通常作为宏实现,并且在使用big endian的平台上将是no-ops。

他们住在:

 #include  

这通常是可用的。

如果你的库有它,你也可以使用 。 使用gcc,这需要-D_BSD_SOURCE

在Unix,BSD和Linux上尝试:man htons man endian man byteorder

如果你真的想这样做,那么你可以使用Intel Mac并为x86和ppc构建。 ppc可执行文件将通过Rosetta仿真运行并将是大端,而本机x86构建当然将是小端。

为什么要在运行时检测平台的字节顺序? 当你去编译时,endian模式是已知的。 您的代码将按照您的预期执行…假设目标平台上的短整数是2个字节。 为了避免这种挂断,你最好看一下最后一个字节。 (byte [sizeof(short int) – 1])