C++ - How to use bitfields

前端 未结 1 513
甜味超标
甜味超标 2021-01-14 21:00

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

1条回答
  •  再見小時候
    2021-01-14 21:50

    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;
        ...
    };
    

    0 讨论(0)
提交回复
热议问题