Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ - How to use bitfields

Tags:

c++

bit-fields

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

like image 222
Q_A Avatar asked Mar 08 '16 01:03

Q_A


1 Answers

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;
    ...
};
like image 196
Barmar Avatar answered Sep 18 '22 16:09

Barmar