"Trick" to use union to verify whether the machine is big or small end

Source: Internet
Author: User

Union u{Short
     A;
     char c;
};
u u;

In the book C programming Language is described in this way:

1) A consortium is a structure;

2 The offset of all its members relative to the base address is 0;

3 This structure space to be large enough to accommodate the most "wide" members;

4 its alignment should be suitable for all the members;

So a federation in memory stored in the form of the following figure:

From the diagram, it's easy to see that the address of variable A, C, and U is 0x20000000

u.a=0x1234;
The small-end mode (the high byte of the data is stored in a high memory address) is stored as follows:

In big-endian mode (the high byte of the data is kept in the low memory address), the storage is as follows:


So, as long as we take out the value of variable C, to compare, if its value is 34h, then the machine is a small-end mode, if its value is 12h, then the machine is big-endian mode.

The implementation code is as follows:

#include <stdio.h>

Union u{
    int A;
    char c;
} u;

int main ()
{
    u.a=0x1234;
    if (0x34 = = u.c)
    {
        printf ("The Machine is little-end.\n");
    }
    else if (0x12 = = u.c)
    {
        printf ("The Machine is big-end.\n");
    }
    return 0;
}


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.