Since x
and y
are ints, you know that the size of the bit field can be no larger than the number of bits in an int.
Since this is C, assume that the right-most bit is #0, so p = 0, n = 1
means to replace the right-most bit in x
.
What you want to do is:
create a bitmask -- a number with the right-most
n
bits set to 1 and all the rest 0;bitwise
and
the bitmask withy
to extract the right-mostn
bits ofy
and shift it leftp
bits;shift the bitmask
p
bits to the left to create a bitmask that will operate onn
bits starting at positionp
;bitwise
and
the inverse shifted bitmask withx
to mask out the bits you want to replace;bitwise
or
the result of 2 and 4 to get your answer.
Rollover to see it in code:
int bitmask = ~((~0) << n); return ((bitmask & y) << p) | (~(bitmask << p) & x);