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

前端 未结 3 1726
遇见更好的自我
遇见更好的自我 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:23

    In general:

    value = (value & ~mask) | (newvalue & mask);
    

    mask is a value with all bits to be changed (and only them) set to 1 - it would be 0xf in your case. newvalue is a value that contains the new state of those bits - all other bits are essentially ignored.

    This will work for all types for which bitwise operators are supported.

提交回复
热议问题