C + + Bit fields

Source: Internet
Author: User

Http://msdn.microsoft.com/en-us/library/ewwyfdbe%28v=vs.71%29.aspx

Note

An unnamed bit field's width 0 forces alignment of the next bit field to the next type boundary, where type< /c4> is the type of the member.

The following example declares a structure that contains bit fields:

 //  bit_fields1.cpp  struct   date{unsigned nweekday:  3    ; //     0..7 (3 bits)  unsigned nmonthday: 6 ; //     0..31 (6 bits)  unsigned nmonth: 5 ; //     0..12 (5 bits)  unsigned nyear: 8 ; //  0..100 (8 bits)   int   Main () {}  

The conceptual memory layout of an object of type are shown in the Date following figure.

Memory Layout of Date Object

Note that nYear is 8 bits long and would overflow the word boundary of the declared type, unsigned int. Therefore, it is begun at the beginning of a new unsigned int.

It's not necessary, all-bit fields fit in one object of the underlying type; New units of storage is allocated, according to the number of bits requested in the declaration.

Microsoft specific

The ordering of data declared as bit are from a low to high bit and as shown in the figure above.

END Microsoft Specific

If the declaration of a structure includes an unnamed field of length 0, as shown in the following example,

//Bit_fields2.cppstructdate{unsigned nweekday:3;//0..7 (3 bits)Unsigned nmonthday:6;//0..31 (6 bits)   unsigned:0; Force alignment to next boundary.Unsigned nmonth:5;//0..12 (5 bits)Unsigned nyear:8;//0..100 (8 bits)};intmain () {}

The memory layout is an as shown in the following figure.

Layout of Date Object with Zero-length Bit Field

The underlying type of a bit field must is a integral type, as described in fundamental Types.

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.