位字段操作

San*_*996 2 c++ bit-fields

在以下代码中

#include <iostream>

using namespace std;
struct field
{
   unsigned first : 5;
   unsigned second : 9;
};
int main()
{
   union
   {
      field word;
      int i;
   };
   i = 0;
   cout<<"First is : "<<word.first<<" Second is : "<<word.second<<" I is "<<i<<"\n";
   word.first = 2;
   cout<<"First is : "<<word.first<<" Second is : "<<word.second<<" I is "<<i<<"\n";
   return 0;
}
Run Code Online (Sandbox Code Playgroud)

当我初始化word.first = 2时,正如预期的那样,它会更新该字的5位,并提供所需的输出.这是'i'的输出有点令人困惑.使用word.first = 2,我将输出设为2,当我执行word.second = 2时,i的输出为64.因为,它们共享相同的内存块,在后一种情况下,输出(对于i)不应该是2?

Oli*_*rth 7

这个特定的结果是特定于平台的; 你应该阅读有关字节序的内容.

但是,为了回答你的问题,没有,word.first并且word.second不共享内存; 他们占据了不同的位.显然,您平台上的底层表示是:

bit   15 14 13 12 11 10  9  8  7  6  5  4  3  2  1  0
     +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
     |     |         second           |    first     |
     +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
     |<------------------- i ----------------------->|
Run Code Online (Sandbox Code Playgroud)

因此设置word.second = 2设置#6的位i,并且2 6 = 64.