## Jun 23, 2021

### K & R : Exercise 2.6 - setbits

K & R : Exercise 2.6 - setbits

## Problem

Write a function setbits(x, p, n, y) that returns x with n bits that begin at position p set to the right most n bits of y, leaving the other bits unchanged.

## Solution

Here, i feel most complicated thing is understanding the question rather than solving it by programming. Let me explain the question visually by an example.

n bits at position p in x has to replaced with n right most bits of y to get the result.

1. First we need to get the Yellow region extracted from X
2. Second we need to get blue region from Y
3. We need to shift the blue region so that it fits between two yellow region
4. We need to 'bitwise OR' 1 and 3.

### Yellow region

We need to create zero mask(means selective bits are zero and rest all are one) of n bits at position p. Expression to that is

((~0 << (p + 1)) | (~(~0 << (p + 1 - n))))


### Blue region

Blue region can be easily extracted from the below expression.

(y & ~(~0 << n))


### Shifting Blue region

This can be very easily gone by

((y & ~(~0 << n)) << (p + 1 - n)


### Putting all together

Now putting all together final program looks like this.

unsigned setbits(unsigned x, unsigned p, unsigned n, unsigned y)
{
return (x & ((~0 << (p + 1)) |
(~(~0 << (p + 1 - n))))) |
((y & ~(~0 << n)) << (p + 1 - n));
}