查看主机字节序

/**************************************************
 * 输出主机字节序
 * 小端字节序(little-endian) 低序字节存储在起始地址(低地址)
 * 大端字节序(big-endian) 高序字节存储在起始地址
 * -----------------------------------------------
 *  0x0102  占两个字节 01是高字节 02是低字节
 *                --------------
 * 小端 地址A --> | 02  |  01  | --> 地址A+1  
 *                --------------
 *				  --------------
 * 大端 地址A --> | 01  |  02  | --> 地址A+1
 *				  --------------
 * ***********************************************/
#include <stdio.h>
#include <stdlib.h>

/* CPU, vendor, and operating system */
#define CPU_VENDOR_OS "sparc64-unknown-freebsd5.1"

int
main(int argc, char **argv)
{
	union {
	  short  s;
      char   c[sizeof(short)];
    } un;

	un.s = 0x0102;
	printf("%s: ", CPU_VENDOR_OS);
	if (sizeof(short) == 2) {
		if (un.c[0] == 1 && un.c[1] == 2)
			printf("big-endian\n");
		else if (un.c[0] == 2 && un.c[1] == 1)
			printf("little-endian\n");
		else
			printf("unknown\n");
	} else
		printf("sizeof(short) = %d\n", sizeof(short));

	exit(0);
}

猜你喜欢

转载自blog.csdn.net/liang_gu/article/details/80592012
今日推荐