【问题标题】:Optimising bitwise operations in C在 C 中优化按位运算
【发布时间】:2013-06-27 04:26:58
【问题描述】:

我遇到了一个问题: “练习 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;
}

但是不知怎么感觉逻辑很长,可以优化,但是暂时还想不到别的办法。 有人可以建议对此进行任何优化吗?

【问题讨论】:

标签: c bitwise-operators bit-shift


【解决方案1】:

制作n 位掩码:

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

p 位开始:

mask_x = mask_y << p;

清除x中的相应位:

x &= ~mask_x;

y中提取位:

y &= mask_y;

将它们上移到p的位置:

y <<= p;

把它们放在一起:

result = x | y;

或者以更紧凑的形式:

mask = (1U << n) - 1;
result = x & ~(mask << p);
result |= (y & mask) << p; 

【讨论】:

  • 假设 32 位整数,如果 n == 32,此解决方案会导致未定义的行为。不过,这种情况只是return y,因此很容易进行特殊情况。或者,使用 1ULL(或者您想要获得 64 位类型)而不是 1U
  • +1 不仅提供了代码,还逐步解释了它的作用
  • 卡尔,你的评论应该是你答案的一部分。
  • 这更像是一个旁白,而不是答案的一部分,真的,这就是我留下评论的原因。 NBD。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-01-09
  • 2021-12-20
  • 1970-01-01
  • 1970-01-01
  • 2021-09-13
相关资源
最近更新 更多