Bit manipulations good practices

后端 未结 7 558
情书的邮戳
情书的邮戳 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 20:57

    Other answers have already covered most of the stuff, but it might be worthwhile to mention that even if you can't use the non-standard 0b syntax, you can use shifts to move the 1 bit into position by bit number, i.e.:

    #define DMA_BYTE  (1U << 0)
    #define DMA_HW    (1U << 1)
    #define DMA_WORD  (1U << 2)
    #define DMA_GO    (1U << 3)
    // …
    

    Note how the last number matches the "bit number" column in the documentation.

    The usage for setting and clearing bits doesn't change:

    #define DMA_CONTROL_REG DMA_base_ptr[DMA_CONTROL_OFFS]
    
    DMA_CONTROL_REG |= DMA_HW | DMA_WORD;    // set HW and WORD
    DMA_CONTROL_REG &= ~(DMA_BYTE | DMA_GO); // clear BYTE and GO
    

提交回复
热议问题