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

前端 未结 7 1335
再見小時候
再見小時候 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条回答
  •  渐次进展
    2021-01-18 19:42

    You could use a bitwise OR:

    a |= (1 << i);
    

    Note that this does not have the same behavior as +, which will carry if there's already a 1 in the bit you're setting.

提交回复
热议问题