Problem
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.
- First we need to get the Yellow region extracted from X
- Second we need to get blue region from Y
- We need to shift the blue region so that it fits between two yellow region
- 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)); }
Links
- Next Article -
- Previous Article - K & R : Exercise 2.5 - alternate strpbrk
- All Article - K & R Answer
Keep blogging..!!
ReplyDeleteBig fan of your blog posts.
amazing explanation man
ReplyDelete