I believe we all know the concept of big-end storage and small-ended storage, this in peacetime, we generally do not consider, but, in some cases, these concepts are very important, for example, in the Socket communication, our computer is a small-end storage mode, but the transmission of data or messages to the other computer, happens, The other side of the computer is big-end storage, then, if you direct transmission, then the other side of the resolution is garbled, so we need to transfer data before the network order.
The purpose of this article is not to solve the problem of dealing with byte order above, but to implement the byte storage order of computer in C language.
There is a structural--union in C that is called a "common body" that can store different types of data like struct, but the size it occupies in memory is the number of bytes of the largest data type (this does not take into account the problem of byte alignment). Thus, we can use this data type to judge.
The specific methods are as follows:
If, now we're storing a variable of integral type, because this integer variable occupies 4 bytes, it should be stored in this way in the computer:
(0x) 0001 low Address---> High-address storage
(0x) 0001 High Address <---Low address small-end storage
So, we can get low address data, testing is 1 or 0, if it is 1, then small-end storage, if it is 0, then is big-endian storage.
Below, give 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 a small-end storage mode ... "<<endl;
}
else if (mu.c = 0)
{
cout<< "Your computer is a big-endian storage mode ... "<<endl;
}
else
{
cout<< "Sorry, there was a mistake ... "<<endl;
}
}
The screenshot that runs on my computer is as follows:
This shows that my computer is "small-end Storage" mode, so, in this way, you can get the computer data storage mode.