When I request or set a single-bit member of a bit-wise struct
/class
, does the compiler do a bit shift? For example, given this struct
:
struct {
unsigned char thing : 4;
unsigned char flag1 : 1;
unsigned char flag2 : 1;
unsigned char reserved : 2;
}
...does the compiler realize that bit-shifting isn't required? In other words, does the compiler do this:
uchar request_flag1() const {
uchar temp = data & 0x40; //0100 0000 - get the 7th bit
return temp >> 7; //0000 0001 - return the shifted value
}
void set_flag1(uchar v) {
data &= 0x191; //1011 1111 - clear the 7th bit
data |= v << 7; //0v00 0000 - set the 7th bit to shifted value
}
or this?
bool request_flag1() const {
return data & 0x40; //0100 0000 - simply check whether the 7th bit is set
}
void set_flag1(bool v) {
if(v) data |= 0x40; //0100 0000 - simply set the 7th bit
else data &= 0x191; //1011 1111 - simply clear the 7th bit
}
I imagine that the latter would be significantly faster since it's half the number of operations.
If the latter is true, would I have to declare the bit field members as type bool
to get this advantage?