I believe everyone knows the concepts of big-end storage and small-end storage. We generally don't need to consider them at ordinary times. However, in some cases, these concepts are very important. For example, during Socket communication, our computer is a small-end storage mode, but when we send data or messages to the other computer, it happens that the other computer is a large-end storage, If you directly transmit, the parsing by the other party is garbled. Therefore, we need to convert the data to the network order before transmitting the data.
The purpose of this article is not to solve the problem of processing the byte sequence, but to use the C language to test the byte storage sequence of the computer.
In the C language, there is a structure called Union, which is called "shared body". It can store different types of data like struct, however, the size occupied by the memory is the number of bytes occupied by the largest data type (here we do not consider the issue of byte alignment ). Therefore, we can use this data type to determine.
The specific method is as follows:
Assume that we store an integer variable because it occupies 4 bytes. Therefore, it should be stored in the computer as follows:
(0x) 0001 low address ---> high address big end Storage
(0x) 0001 high address <--- low address small-end Storage
Therefore, we can obtain low-address data. The test value is 1 or 0. If the value is 1, it means small-end storage. If the value is 0, it means large-end storage.
Below is the test code:
# Include <iostream> using namespace std; void checkSystemBigOrLittle (void); int main (void) {checkSystemBigOrLittle (); system ("pause"); return 0 ;} void checkSystemBigOrLittle (void) {typedef union MyUnion {int I; char c ;}; MyUnion mu; mu. I = 1; if (mu. c = 1) {cout <"your computer is in small-end storage mode... "<Endl;} else if (mu. c = 0) {cout <" your computer is in the big-end storage mode... "<Endl;} else {cout <" sorry, error... "<Endl ;}# include <iostream> using namespace std; void checkSystemBigOrLittle (void); int main (void) {checkSystemBigOrLittle (); system (" pause "); return 0;} void checkSystemBigOrLittle (void) {typedef union MyUnion {int I; char c ;}; MyUnion mu; mu. I = 1; if (mu. c = 1) {cout <"your computer is in small-end storage mode... "<Endl;} else if (mu. c = 0) {cout <" your computer is in the big-end storage mode... "<Endl;} else {cout <" sorry, error... "<Endl ;}}
Running on my computer is as follows: