Reputation: 8279
K&R's exercise 2-6:
Write a function
setbits(x,p,n,y)
that returnsx
with then
bits that begin at positionp
set to the rightmostn
bits ofy
, leaving the other bits unchanged.
Here is my interpretation of an example input/output:
unsigned x = 315;
int p = 2;
int n = 3;
unsigned y = 9;
printf("%d\n", setbits(x, p, n, y)); // 295
And here is my reasoning.
3 bits at position 2 for 315:
0000 0001 0011 1011
- --
3 rightmost bits for 9:
0000 0000 0000 1001
---
Set 3 rightmost bits for 9 to the 3 bits starting at 2 for 315 => 295:
0000 0001 0010 0111
- --
I wrote some code and then wanted to check it against other solutions, for example. The two that I found online both give a different answer, 313:
0000 0001 0011 1001
--- ???
What am I missing?
Upvotes: 0
Views: 222
Reputation: 3132
The specification of the problem is a bit ambiguous. You are interpreting "the n bits starting at position p" to signify bits p, p+1, ..., p+n-1. The page you linked to seems to say the n bits starting at position p are bits p, p-1, ..., p-n+1. So the 3 bits starting at bit 2 would be bits 2, 1, 0, the rightmost three bits.
Upvotes: 1