What is the best way to set a particular bit in a variable in C

前端 未结 7 1327
再見小時候
再見小時候 2021-01-18 19:02

Consider a variable unsigned int a; in C.

Now say I want to set any i\'th bit in this variable to \'1\'.

Note that the variable has some value.

7条回答
  •  萌比男神i
    2021-01-18 19:41

    Some useful bit manipulation macros

    #define BIT_MASK(bit)             (1 << (bit))
    #define SET_BIT(value,bit)        ((value) |= BIT_MASK(bit))
    #define CLEAR_BIT(value,bit)      ((value) &= ~BIT_MASK(bit))
    #define TEST_BIT(value,bit)       (((value) & BIT_MASK(bit)) ? 1 : 0)
    

提交回复
热议问题