How to set and clear different bits with a single line of code (C)

前端 未结 2 776
不思量自难忘°
不思量自难忘° 2021-01-22 07:19

data |= (1 << 3) sets bit (3) without disrupting other bits. data &= ~(1 << 4) resets bit (4) without disrupting other bits. How can I

2条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-01-22 07:52

    It's not possible in a single instruction. This is because there are 3 possible operations you need to do on the different bits:

    • Set them (bit 3)
    • Clear them (bit 4)
    • Leave them alone (all the other bits)

    How can you select from one of three possibilities with a bitmask made up of binary digits?

    Of course, you can do it with one line e.g:

    data = (data | (1 << 3)) & ~(1 << 4)
    

提交回复
热议问题