[Big endian and little endian storage] C language


Preface

Let’s first introduce the concepts of big endian and little endian through a question, as shown below

Please briefly describe the concepts of big-endian and little-endian, and design a small program to determine the byte order of the current machine.


1. The concepts of big endian and little endian.

Big-endian (storage) mode means that the low-order bits of data are stored in the high addresses of the memory, and the high-order bits of the data are stored in the low addresses of the memory; little-endian (storage) mode means that the low-order bits of the data are stored in the low addresses of the
memory
. address, and the high bits of the data are stored in the high
addresses of the memory.

1. Detailed explanation of big endian and little endian

We know that the way data is stored in computers is in the form of two's complement codes.(If you don’t understand the complement code, you can read the introduction of bit operators in this article ). For example, the integer data 2 is stored in the memory in the form of
0000 0000 0000 0000 0000 0000 0000 0010. We convert the two’s complement code into a ten The hexadecimal number is 00 00 00 02.
But when we debugged it in the VS 2022 environment, we found that the hexadecimal digits of the number 2 stored in the memory are as follows:
The number 2 in memory
In the above figure, you can see that the number 2 is The storage format in the memory is 02 00 00 00 , which is exactly the opposite order of the 00 00 00 02 we calculated above , but not every bit is in the opposite format, such as 20 00 00 00. This is because in the memory Our data is stored in bytes as a whole, and our IDE: VS 2022 is stored in the form of little endian, that is, the high bits are placed at high addresses and the low bits are placed at low addresses.

2. Write a program to determine the byte order of the current machine

#define _CRT_SECURE_NO_WARNINGS 1
#include <iostream>
using namespace std;
int main()
{
    
    
	int a = 1;
	char* p = (char*)&a;//用char型的指针访问a的首地址,如果拿到的是01则是小端,如果是00则是大端
	if (*p == 0)
	{
    
    
		cout << "大端存储" << endl;
	}
	else if (*p == 1)
	{
    
    
		cout << "小端储存" << endl;
	}
	return 0;
}

The running results are as follows:
Insert image description here

Guess you like

Origin blog.csdn.net/weixin_63614711/article/details/128558009