Union and big-endian, littleendian

Source: Internet
Author: User

Union and big-endian, littleendian

1. Basic Features of union -- same and different from struct

Union, the Chinese name "consortium, shared body", in a way similar to a structure struct data structure, shared body (union) and struct (struct) it can also contain many data types and variables.

When the members are identical, struct takes up more memory than union.

The reason is that the memory allocation mechanisms of struct and union in C are different:

In struct, all members have their own storage space. To facilitate addressing and management, all data members must follow the memory alignment rules;

In union, all members share a bucket. When operating on different members, the compiler takes different values based on different member types.

2. memory space occupied by union:

#include<stdio.h>union unionTest{        int a;        double b;}main(){        union unionTest test;        printf("The sizeof of test is %d\n",sizeof(test));       }

Result:

The sizeof of test is 8

Note: The size of memory space allocated by the consortium is the size of the largest member in the consortium.

3. union and big-endian ): 

# Include <stdio. h> union var {char c [4]; int I ;};
Int main () {union var data; data. c [0] = 0x04; // because it is of the char type, the number should not be too large, and the ascii range is calculated ~ Data. c [1] = 0x03; // It is written in hexadecimal notation to facilitate direct printing of values in the memory to compare data. c [2] = 0x02; data. c [3] = 0x11; // in the array, the subscript is low and the address is low. The memory content is as follows:, and by address. Four bytes in total!
// Take the four bytes as a whole (regardless of the type, directly print the hexadecimal format), it should be seen from the memory high address to the low address, 0x11020304, set low-level 04 to low-level address. Printf ("% x \ n", data. I );}

Result:

11020304

It indicates that my 32-bit win7 system is a small-end mode.

 

 

 

Related Article

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.