[Tip] If you use union to determine if machine memory is big-endian or small-endian storage @ C

Source: Internet
Author: User

such as int i = 1, if it is small-endian storage, then in memory should be this: 0x01 0x00 0x00 0x00, if it is the big-endian storage, in memory should be: 0x00 0x00 0x00 0x01.

So how to program to determine whether the machine is big-endian storage or small-order storage it?

On the code:

 #include <stdio.h>int   Isbigendian (        {Union { int   I;     char   C;        }test;    test.c  = 1  ;  return  test.i! = 1  ;} int   Main () {printf ( "  %d\n   , Isbigendian ());}  

Since both int and Char in the union are stored from the low address, if it is a small-endian store, the TEST.C is assigned to one, then the Union should be 0x01 0x00 0x00 0x00 0x00 0x00 0x00 0x00, Then the value of TEST.I should also be 1, then test.c==test.i. In the case of big-endian storage, the Union should look like this in memory: 0x00 0x00 0x00 0x01 0x00 0x00 0x00 0x00, then the value of TEST.I should be 2 of 8 square, i.e. test.i==256. That is, if it is a big endian store, test.i! = test.c. If test.i! = test.c, then store for the big endian, or small-endian if equal.

[Tip] If you use union to determine if machine memory is big-endian or small-endian storage @ C

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.