C++ - How to use bitfields

江枫思渺然 提交于 2020-03-21 01:49:14

问题


So I recently came across something like this

unsigned char ch : 7;

inside a struct. I read about it a little. Apparently these are called bit fields. They are used to set the width of data that a char can receive. But how do we use these things. For example, I know that we can set variable ch to be a byte

unsigned char ch = 0x61;
cout << ch << endl;

This will output

a

However, what do we do with the bitfields?

unsigned char ch : 7;
ch = 0x61;                //This doesn't work for some reason

unsigned char ch : 7;
unsigned char ch = 0x61/  //Neither does this.

Thanks for the help


回答1:


Bitfields can only be used inside structured data types, i.e. struct, class, and union types. The purpose is to allow you to pack multiple members inside a single byte, without having to write lots of explicit shifts and masks. For instance, you can write:

struct halfbyte_t {
    unsigned int half1: 4;
    unsigned int half2: 4;
} halfbyte;

This declares a variable named halfbyte that contains two 4-bit members, which will be packed into a single 8-bit byte, rather than having to use 2 bytes if you just declared them unsigned char.

You access them just like any other structure member:

halfbyte.half1 = 3;
cout << halfbyte.half3;

1-bit fields are especially useful if you have lots of boolean flags in a structure, since you don't have to have a separate byte for each flag.

struct flag_t {
    unsigned int flag1: 1;
    unsigned int flag2: 1;
    unsigned int flag3: 1;
    unsigned int flag4: 1;
    ...
};


来源:https://stackoverflow.com/questions/35857111/c-how-to-use-bitfields

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!