主机字节序大端和小端

    在内存中有两种存储整数的方式,一种是将低序字节存储在起始位置,这称为小端字节序,另一种方法是将高序字节存储在起始位置,这成为大端字节序。如何判断所使用的机器是大端字节序还是小端字节序呢?以下程序使用联合体判断当前机器是大端还是小端。
#include <iostream>
using namespace std;

int main(void)
{
	union{
		short s;
		char c[2];
	} un;
	un.s = 0x0102;
	if (un.c[0] == 2 && un.c[1] == 1)
	{
		cout << "小端" << endl;
	}
	else if (un.c[0] == 1 && un.c[1] == 2)
	{
		cout << "大端" << endl;
	}
	else
	{
		cout << "错误" << endl;
	}
	system("pause");
	return 0;
}

猜你喜欢

转载自blog.csdn.net/yang20141109/article/details/77126967
今日推荐