jds
jds

Reputation: 8279

K&R's exercise 2-6: Do not understand input/output

K&R's 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.

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

Answers (1)

David K
David K

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

Related Questions