Take the 2-minute tour ×  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 bits unaffected. How would I do this the fastest in
C?  share|improve this question add comment  2 Answers  up vote
6 down vote accepted  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.    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. share|improve this answer add comment  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 essen