大端小端

大端小端_第1张图片


#include 

#include 
#include 
#include 
using namespace std;

#pragma comment(lib,"ws2_32.lib")


void main(){
	//大端小端
	char *buf = new char[3];

	//char buf[3]={0};
	/*
	1 字节=8 bit位
	unsigned short 2字节 = 16位
	
	十六进制:0x1234
	二进制:  0001 0010 0011 0100
	*/
	unsigned short len = 0x1234; //十进制4660

	//小端,内存高地址存储高位字节0x12  内存低地址存储低位字节0x34
	*(unsigned short*)buf = len;
	cout<<"\n\n小端:";
	printf("0x%x\n",len);
	printf("buf[0] = 0x%x, buf[1] = 0x%x\n",buf[0],buf[1]);
	cout<<buf[0]+buf[1]*256<<endl;//高位在高地址

	cout<<"\n\n大端:";
	//大端,内存高地址存储低位字节0x34  内存低地址存储高位字节0x12
	*(unsigned short*)buf = htons(len);

	printf("0x%x\n",len);
	printf("buf[0] = 0x%x, buf[1] = 0x%x\n",buf[0],buf[1]);
	cout<<buf[0]*256+buf[1]<<endl;//高位在低地址

	while(1);
}




输出

小端:0x1234
buf[0] = 0x34, buf[1] = 0x12
4660


大端:0x1234
buf[0] = 0x12, buf[1] = 0x34
4660

你可能感兴趣的:(C)