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

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

    You could probably use

    a |= (1 << i)
    

    But it won't make much of a difference. Performance-wise, you shouldn't see any difference.

    You might be able to try building a table where you map i to a bit mask (like 2 => 0x0010 for 0000000000100), but that's a bit unnecessary.

    0 讨论(0)
提交回复
热议问题