cbinarybit-manipulationkr-c

K&R C Exercise Help


I've been going through the K&R C Programming Language book and I'm stuck on Exercise 2-6 which reads:

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.

I'm having trouble understanding the exact thing they're looking for me to do. I looked at a possible answer here, but I still don't really understand. I think it's the wording that's throwing me off. Can anyone maybe explain what they're looking for me to do in a different way? I'm hoping that different wording will help me understand what I need to do code wise.


Solution

  • Expounding on Avi's answer:

    int i = setbits(0xAB = b10101011, 5, 3, 0xAA = b10101010);
    i equals 0x93 = b10010011
    

    Say your i = 0xAB. In binary, this is: 10101011

    Let's number each of the bit positions.

    Position #: 7   6   5   4   3   2   1   0
    Bit:        1   0   1   0   1   0   1   1
    

    The right-most bit (the least-significant) is position "0". The left-most (most-significant) is position "7".

    So the next two values, p and n, are saying "You want to modify n bits starting at bit p." So if p=5 and n=3, you want to start at bit number 5, and in total you're modifying 3 bits. Which means bits 5, 4, 3. "101" in this example.

    Position #: 7   6   5   4   3   2   1   0
    Bit:        1   0   1   0   1   0   1   1
                       |         |
                        ---------
                   (Modifying these three bits)
    

    How are we modifying them? We are replacing them. With another set of 3 bits. The three least-significant bits from y.

    So here's y:

    Position #: 7   6   5   4   3   2   1   0
    Bit:        1   0   1   0   1   0   1   0 
    

    And the right-most bits would be bits 2, 1, 0. or the value "010". Of course, if the value of n=6, then you'd want to replace those six bits from i with "101010" - the rightmost 6 bits.

    So your task is to take the specified bits from i - in this case, "101" - and replace them with the specified bits in y - "010".

    If you do this, then your return value is

    1 0 1 0 1 0 1 0