union and endianness

  union is a keyword in C language, its usage is actually very similar to struct.
  All data members in the union share one space, only one of them can be stored at the same time, and all data members have the same starting address. E.g:

union U
{
     double d;
     int i;
     char c;
     float f;
}u;

  We can use sizeof to detect the size of the above example, and we can find that its size is the size of the largest double type, which is 8 bytes.
  


The effect of big and small end heap union type data

First explain what is big and small endian?

The high byte of big endian word data is stored in the low address , and the low byte of the word data is stored in the high address . The high byte of the
little- endian word data is stored in the high address , and the low byte of the word data is stored in the low address .

  The space occupied by the union type data is equal to the space occupied by its largest member, and the access to the union type member starts from the offset 0 relative to the base address of the union, that is to say, for the access to the union, No matter which variable it is, it starts from the first address of the union, so the difference in the size of the machine will affect the data of the union type. As an example:

void test()
{
     union
     {
          int i;
          char a[2];
     }*p, u;
     p = &u;
     p->a[0] = 0x39;
     p->a[1] = 0x38;
     printf("%x", p->i);
}

What data will this program print?
  Through the vs2013 test, it is found that 0xcccc3839 is printed. We open the memory window, and through debugging, we can find that the left side of the first line of memory is the low address, and the right side is the high address, while the high byte of the printed data is stored in the high address of the memory, and the low byte is stored in the low address of the memory. In the address, from this, it can also be judged that my computer is little endian.
As for the result of running on a big-endian computer, it can also be seen by inference that it is 0x3938cccc


  Now there is a question: please write a C function, if the processor is big endian, it will return 0; if it is little endian, it will return 1.
This problem, we can solve through the union. First, let's define a variable of type int and see how it is stored in memory?

  Through the characteristic that all members of the union have the same starting address, at this time, we take the lowest byte, and we can find that if it is big endian, we get 0, and if it is little endian, we get 1.
code show as below:

int CheckSystem()
{
     union check
     {
          int i;
          char c;
     }c;
     c.i = 1;
     return c.c;
}

The test found that the results were correct:
write picture description here

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325627088&siteId=291194637