码迷,mamicode.com
首页 > 编程语言 > 详细

C++ Bit Fields

时间:2014-08-12 00:19:13      阅读:296      评论:0      收藏:0      [点我收藏+]

标签:des   style   blog   http   color   os   io   strong   

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

Note   

An unnamed bit field of width 0 forces alignment of the next bit field to the next type boundary, where type 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 Date is shown in the following figure.

Memory Layout of Date Object

bubuko.com,布布扣

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 is not necessary that all bit fields fit in one object of the underlying type; new units of storage are allocated, according to the number of bits requested in the declaration.

Microsoft Specific

The ordering of data declared as bit fields is from low to high bit, 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.cpp
struct Date
{
   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)
};

int main()
{
}

the memory layout is as shown in the following figure.

Layout of Date Object with Zero-Length Bit Field

bubuko.com,布布扣

 

 

The underlying type of a bit field must be an integral type, as described in Fundamental Types.

 

C++ Bit Fields,布布扣,bubuko.com

C++ Bit Fields

标签:des   style   blog   http   color   os   io   strong   

原文地址:http://www.cnblogs.com/shangdawei/p/3905784.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!