大端与小端

一、大端模式和小端模式的起源
关于大端小端名词的由来,有一个有趣的故事,来自于Jonathan Swift的《格利佛游记》:Lilliput和Blefuscu这两个强国在过去的36个月中一直在苦战。战争的原因:大家都知道,吃鸡蛋的时候,原始的方法是打破鸡蛋较大的一端,可以那时的皇帝的祖父由于小时侯吃鸡蛋,按这种方法把手指弄破了,因此他的父亲,就下令,命令所有的子民吃鸡蛋的时候,必须先打破鸡蛋较小的一端,违令者重罚。然后老百姓对此法令极为反感,期间发生了多次叛乱,其中一个皇帝因此送命,另一个丢了王位,产生叛乱的原因就是另一个国家Blefuscu的国王大臣煽动起来的,叛乱平息后,就逃到这个帝国避难。据估计,先后几次有11000余人情愿死也不肯去打破鸡蛋较小的端吃鸡蛋。这个其实讽刺当时英国和法国之间持续的冲突。Danny Cohen一位网络协议的开创者,第一次使用这两个术语指代字节顺序,后来就被大家广泛接受。

二、什么是大端和小端
Big-Endian和Little-Endian的定义如下:

  1. Little-Endian就是低位字节排放在内存的低地址端,高位字节排放在内存的高地址端。
  2. Big-Endian就是高位字节排放在内存的低地址端,低位字节排放在内存的高地址端。

三程序验证:

打开vs2008,新建控制台应用程序


// include WinSock library head files.
#include "WinSock2.h"
#include "iostream"
// link WinSock load library
#pragma comment(lib, "ws2_32.lib")

using namespace std;





int main(int argc, char **argv)
{
	/**load WinSock dll*/
# if 0
	WSADATA wsaData;
	WORD wVersionRequested = MAKEWORD(2,2);
	if (WSAStartup(wVersionRequested, &wsaData)!=0)
	{
		cout << "load WinSock dll failed." << endl;
		return 0;
	}
#endif
	// define unsigned short int type variable x, y, 
	// and initialize y decimal 0x1234
	u_short x, y = 0x1234;
	// convert the value of y to network byte order 
	x = u_short(htons(y));
	cout << "host byte order:" << hex << y << "\t network byte order:" << x << endl;
	u_long a, b = 0x1122ABCD; 
	a =u_long( htonl(b) );
	cout << "host byte order:" << hex << b << "\t network byte order:" << a << endl;
	//WSACleanup();


	return 0;
}


参考:

http://blog.csdn.net/ce123_zhouwei/article/details/6971544

posted @ 2017-02-21 15:46  drfxiaoliuzi  阅读(218)  评论(0编辑  收藏  举报