What is endianness? How to tell?

1. What exactly is big and small endian?

First we need to know that data can be stored in memory. In a computer system, the smallest storage unit of memory is a byte, that is, one address corresponds to a byte, and one byte (8Bit) of data can be saved. However, in a computer system, it is impossible to store everything in one byte. , and some 8-bit, 16-bit, and 32-bit systems will also have 2-byte and 4-byte variables. So there is a saying about the order in which data is stored in memory, which is the origin of big and small endianness.

The following is an example to illustrate the principle of big and small endianness.

For example, there is a 16-bit integer 0x1234 consisting of 2 bytes. Then the way it is stored in memory is:

        1) Store the high byte 0x12 at the high address, and store the low byte 0x34 at the low address;

        2) Store the high byte 0x12 at the low address, and store the low byte 0x34 at the high address;

The demonstrations of 1) and 2) are as shown below:

In the picture above, the storage method of (1) is little endian, and the storage method of (2) is big endian.

For another example, there is a 32-bit int type number 0x12345678. Assume that its MSB (Most Significant Byte, the most significant byte) is 0x12, and its LSB (Least Significant Byte, the least significant byte) is 0x78. There are two types in the CPU memory. The storage method is as follows:

To sum up, in summary:

大端:是高字节数据存放到内存的低地址,低字节数据存放在内存的高地址;
小端:是高字节数据存放到内存的高地址,低字节数据存放在内存的低地址;

2. How to determine the big and small endian modes of the CPU?

When we write code, we don’t know whether the current environment is in big-endian mode or little-endian mode. Sometimes when we use some data structures, assignment errors will occur when assigning values, so we need to detect the size of the current system. end, which makes it easier for us to arrange the writing of data structures when writing code.

Regarding the judgment of big and small endian, once you know the principle of big and small endian, it is actually very simple to verify. You can test it by writing a code segment.

I personally think that the easiest way to determine the endianness is to use the shared memory space mechanism of the union to determine the endianness. In addition, it is also very convenient to use pointers. The two are similar, as follows:

(1) Use the union

typedef union
{
        
        
	int a;
	char b;
}test;

// 给a赋值
test.a = 0x12345678

// 判断b的值
print(test.b) // 如果test.b=0x12说明是大端,如果test.b=0x78说明是小端

(2) How to use pointers

int a = 0x12345678;
char *b = (char *)(&a);		// 指针方式其实和共用体的本质很像

if(0x78 == *b)
    小端模式;
else if(0x12 == *b)
    大端模式;

 

Guess you like

Origin blog.csdn.net/weixin_43866583/article/details/128851712