Bit manipulations good practices

后端 未结 7 537
情书的邮戳
情书的邮戳 2021-02-03 20:28

As a beginner C programmer, I am wondering, what would be the best easy-to-read and easy-to-understand solution for setting control bits in a device. Are there any standards

7条回答
  •  不思量自难忘°
    2021-02-03 21:08

    The old-school C way is to define a bunch of bits:

    #define WORD  0x04
    #define GO    0x08
    #define I_EN  0x10
    #define LEEN  0x80
    

    Then your initialization becomes

    DMA_base_ptr[DMA_CONTROL_OFFS] = WORD | GO | LEEN;
    

    You can set individual bits using |:

    DMA_base_ptr[DMA_CONTROL_OFFS] |= I_EN;
    

    You can clear individual bits using & and ~:

    DMA_base_ptr[DMA_CONTROL_OFFS] &= ~GO;
    

    You can test individual bits using &:

    if(DMA_base_ptr[DMA_CONTROL_OFFS] & WORD) ...
    

    Definitely don't use bitfields, though. They have their uses, but not when an external specification defines that the bits are in certain places, as I assume is the case here.

    See also questions 20.7 and 2.26 in the C FAQ list.

提交回复
热议问题