C language---big-endian little-endian

The existence of big-endian and little-endian is to solve the problem of byte storage arrangement in the computer. Many arm, dsp, and x86 systems adopt little-endian mode, while keil C51 adopts big-endian mode, and general operating systems adopt little-endian mode. The communication protocol is big-endian.

Big endian: the low byte is stored at the high address end of the memory, and the high byte is stored at the low address end of the memory (low high, high low)

Little endian: the low byte is stored at the low address end of the memory, and the high byte is stored at the high address end of the memory (low low, high high)

For example: 0x1234

0x1234 Low address High address
Little endian 34 12
Big endian 12 34

 

How to verify the endianness of the machine?

1. Use pointers

#include<stdio.h>

int main(int argv,char *argc[])
{
	int a = 20;//0x0014   
	char *p = (char *)&a;
	//通过验证最低位是0还是1
	printf("p = %x",*p);
	printf("p+1 = %x",*(p+1));
	if(*p == 20)
	{
		printf("小端模式\n");
	}
	else
	{
		
		printf("大端模式\n");
	}

    return 0;
}

2. Use a consortium

Union: Union is to store different types of data in the same storage space, the space occupied by the union data type is equal to the space occupied by its largest member, and the union access starts from the base address (starting from the first address)


#include<stdio.h>

int main(int argv,char *argc[])
{
	union{
		short a;
		char b[2];
	}u;
	u.b[0]= 0x12;
	u.b[1]= 0x34;
	
	printf("0x%x\n",u.a);

    return 0;
}

3. Use functions

Host byte order: little endian

Network byte order: big endian

htonl() //The conversion from the host byte order of the 32-bit unsigned integer to the network byte order (little endian->>big endian)
htons() //The host byte order of the 16-bit unsigned short integer to Network byte order conversion (little endian->>big endian)
ntohl() // 32-bit unsigned integer network byte order conversion to host byte order (big endian->> little endian)
ntohs() //Conversion from the network byte order of the 16-bit unsigned short integer to the host byte order (big endian->>little endian
 

#include<stdio.h>
#include <arpa/inet.h>


int main(int argv,char *argc[])
{
	union{
		short a;
		char b[2];
	}u;
	u.b[0]= 0x12;
	u.b[1]= 0x34;
	
	printf("0x%x\n",u.a);
	printf("0x%x\n",htons(u.a));

    return 0;
}

Guess you like

Origin blog.csdn.net/qq_45604814/article/details/112388819