开发者

Simple C syntax Question

I ran into the following code in an old exam of the C course I'm taking:

struct QuestionSet{
    char q1:1;
    char q2:1;
    char q3:1;
}

I have no idea what the syntax开发者_如何学Python "char q1:1" means, and I haven't been able to find it anywhere in "The C Programming Language" which is the course book. Can anyone explain?


It's a bitfield. The number after the colon indicates the number of bits to assign to the struct element. So the three elements are all one bit wide, and are able to store two values: 0, and either 1 or -1 (depending on your compiler, though -1 would be the more logical option when considering two's-complement arithmetic).


Bitfields are often used in microcontrollers programming, because it helps mapping registers in memory. For example, for a 8 bits register, if each bit has a different meaning/usage, it is possible to represent the register value with a structure:

struct exception_register
{
    bool enable_irq_0: 1;
    bool enable_irq_1: 1;
    bool enable_irq_2: 1;
    bool enable_irq_3: 1;
    bool irq_flag_0: 1;
    bool irq_flag_1: 1;
    bool irq_flag_2: 1;
    bool irq_flag_3: 1;
};

byte* the_register = 0x1234; // where 0x1234 is the address of the register in memory.

Then enabling exceptions 2 can be done like this:

the_register->enable_irq_2 = true;

Which is more readable than:

*the_register |= (1 << 2);

This is not intended to answer the question, but may help to understand why bitfields can be usefull.


It seems to be a bitfield. Example Bitfield

Bitfield may be useful on small memory.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜