8

I had a problem in hand as this : "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."

I've written a function for this as below. This is working as expected.

int func_setx(int x,int p,int n,int y)
{
    int a_t= ~0 << (p+n);
    int b_t= ~a_t >> n;
    int x_t= x& (a_t | b_t);    // a temporary x which has the bits to be changed as 0 , rest of the bits unchanged.

    int mask= (y << p) & (~(~0 << (p+n)));     // a mask which has required bits from y in positions to be set , rest all bits 0.

    printf("\nCheckpoint : mask= %x  x_t= %x\n",mask,x_t);

    int result= mask|x_t;
    return result;
}

But I somehow feel the logic is long and can be optimized, but can't think of any other way yet. Can anyone suggest any optimization to this please?

2

1 Answer 1

10

To make an n bit mask:

mask_y = (1U << n) - 1;

To start it at bit p:

mask_x = mask_y << p;

Clear the appropriate bits in x:

x &= ~mask_x;

Extract the bits from y:

y &= mask_y;

Upshift them to position p:

y <<= p;

Put it all together:

result = x | y;

Or in a more compact form:

mask = (1U << n) - 1;
result = x & ~(mask << p);
result |= (y & mask) << p; 
Sign up to request clarification or add additional context in comments.

4 Comments

Assuming 32-bit integers, if n == 32, this solution causes undefined behaviour. That case is just return y, though, so it's easy to special-case. Alternately, use 1ULL (or however you want to get a 64-bit type) instead of 1U.
+1 for not just giving the code but also explaining what it does step-by-step
Carl, your comment should properly be part of your answer.
It's more of an aside than part of the answer, really, which is why I left it a comment. NBD.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.