There are two types of processors:
Patterns of Big_endian and Little_endian
The Big_endian mode stores the operands from high to low bytes. The high byte holds the low of the number, and the lower byte holds the high of the data.
The Little_endian mode stores the operands from low to high bytes. Low bytes hold the low of the number and high bytes hold the data high.
such as: 0x1234
Memory Address: 0x4000 0x4001
Little_endian:0x4000:0x34 0x4001:0x12
big_endian:0x4000:0x12 0x4001:0x34
The Union union is stored in the order that all members are stored from the low address. The data members of a consortium (a common body) are stored from the low address.
Use Union to view the mode of the CPU. Returns 0 if the processor is Big_endian, 1 if Little_endian
The code is as follows:
#include <iostream>
using namespace std;
int Checkcpu ()
{
Union w
{
int a;//4 bytes
char b;//1 bytes
}c;
c.a=1;
return (c.b==1);
}
int main (int argc, char* argv[])
{
int i;
I=checkcpu ();
if (i==1)
{
cout<< "Little_endian" <<endl;
}
else
{
cout<< "Big_endian" <<endl;
}
return 0;
}
If the big-endian mode, from low address to high address c.a stored as 0x00 0x00 0x00 0x01,c.b is assigned to 0x00
If the small-end mode, from low address to high address c.a stored as 0x01 0x00 0x00 0x00,c.b is assigned to 0x01
Here's an example:
#include <iostream>
using namespace std;
void Checkcpu ()
{
Union w
{
char b[4];//1 bytes
int a;//4 bytes short
int d;//2 bytes
}c;< c9/>c.b[0]=2;
C.b[1]=1;
c.b[2]=3;
c.b[3]=0;
cout<< "C.a=" <<c.a<<endl;
cout<< "c.d=" <<c.d<<endl;
}
int main (int argc, char* argv[])
{
checkcpu ();
return 0;
}
Output:
c.a=196866
c.d=258
The data in B is: 0x02 0x01 0x03 0x00
A:4 a byte, so,
Big_endian: In-memory data stored as: 0x02 0x01 0x03 0x00
Little_endian: In-memory data stored as: 0x00 0x03 0x01 0x02 c.a=0x00 0x03 0x01 0x02 =196866
D:2 a byte, so,
Big_endian: In-memory data stored as: 0x02 0x01 0x03 0x00
Little_endian: In-memory data stored as: 0x01 0x02 0x00 0x03 c.d=0x01 0x02=258