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

前端 未结 7 1347
再見小時候
再見小時候 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:56

    The most common way to do this is:

    a |= (1 << i);
    

    This is only two operations - a shift and an OR. It's hard to see how this might be improved upon.

提交回复
热议问题