Let's go through one exercise, for a sample.
Exercise 2-6: Write a function
setbits(x, p, n, y) that returns x
with the n bits that begin at position
p set to the rightmost n bits of y,
leaving the other bits unchanged.
Let's keep in mind that the least significant bit is bit 0 (is at position 0).
Here is the pseudocode:
- Move the bits p to p+n in x to position 0 to n. That's where you right-shift.
- Prepare a bit mask that will turn anything from bit n to the highest bit into 0s. You can use a lookup array for this (for example, 0xFF for n=8, 0x7F for 7 and so on), or you can use a combination of setting bit 0 and left-shifting in a loop.
- Apply the bit mask to
x using &. All the bits we don't care about in x are now 0.
- Invert the bit mask. We now have a bunch of 1s at the high end, and a bunch of 0s at the low end. The bits we want to change in y all have 0s in bit mask.
- Apply the bit mask to y using & . All the bits in y that we will replace with bits in x are now set to 0, and the bits that we don't want to change are unchanged.
- Set the bits we want to change in y by combining x and y using
|. This is the crucial point - go over what's happening with a pen and paper. The bits in x that were set to 0 in (3) will not affect the corresponding bits in y. The bits in x that were not affected by (3) will combine with 0s in y (0s because of step5), setting the resulting bit to the value it had in x.