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?
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With