优化C中的按位运算

Diw*_*rma 8 c bit-shift bitwise-operators

我手头有一个问题:"练习2-6.写一个函数setbits(x,p,n,y)返回x,其中n位从位置p开始设置为y的最右边n位,离开其他位不变."

我已经为此编写了一个函数,如下所示.这是按预期工作的.

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;
}
Run Code Online (Sandbox Code Playgroud)

但我不知何故觉得逻辑很长并且可以优化,但还不能想到任何其他方式.有人可以建议任何优化吗?

Car*_*rum 10

制作一个n掩码:

mask_y = (1U << n) - 1;
Run Code Online (Sandbox Code Playgroud)

从头开始p:

mask_x = mask_y << p;
Run Code Online (Sandbox Code Playgroud)

清除以下内容中的相应位x:

x &= ~mask_x;
Run Code Online (Sandbox Code Playgroud)

y以下位置提取位:

y &= mask_y;
Run Code Online (Sandbox Code Playgroud)

将它们升级到位置p:

y <<= p;
Run Code Online (Sandbox Code Playgroud)

把它们放在一起:

result = x | y;
Run Code Online (Sandbox Code Playgroud)

或者以更紧凑的形式:

mask = (1U << n) - 1;
result = x & ~(mask << p);
result |= (y & mask) << p; 
Run Code Online (Sandbox Code Playgroud)