How do you set only certain bits of a byte in C without affecting the rest?

前端 未结 3 1713
遇见更好的自我
遇见更好的自我 2020-11-30 07:04

Say I have a byte like this 1010XXXX where the X values could be anything. I want to set the lower four bits to a specific pattern, say 1100, while leaving the upper four bi

3条回答
  •  情歌与酒
    2020-11-30 07:13

    You can set all those bits to 0 by bitwise-anding with the 4 bits set to 0 and all other set to 1 (This is the complement of the 4 bits set to 1). You can then bitwise-or in the bits as you would normally.

    ie

     val &= ~0xf; // Clear lower 4 bits. Note: ~0xf == 0xfffffff0
     val |= lower4Bits & 0xf; // Worth anding with the 4 bits set to 1 to make sure no
                              // other bits are set.
    

提交回复
热议问题