【问题标题】:Write a func invert(x,p,n) that returns x with the n bits that begin at position p inverted (1 becomes 0 & vice-versa), leaving the others unchanged编写一个 func invert(x,p,n) 返回 x,其中从位置 p 开始的 n 位反转(1 变为 0,反之亦然),其他保持不变
【发布时间】:2021-06-07 08:43:47
【问题描述】:

以下问题的解决方案是否正确?

我的解决办法是:

#include <stdio.h>

unsigned invert(unsigned x, int p, int n)
{
    return (x >> (p + 1 - n)) ^ ~(~0 << n);
}

int main()
{ 
    printf("%d\n", invert(6, 4, 3));
    return 0;
}

打印输出6,0110 的二进制等价物。

【问题讨论】:

  • 你得到什么输出,你期望什么输出? Edit你的问题,让我们知道。
  • 不,您的解决方案是错误的,至少因为 x 被转移了。位置是如何编号的,位置 0 是 LSB 吗?正确的结果是什么? (我会说它是 26,二进制 00011010。)
  • p 是如何解释的?它是从 LSB 的第 0 位开始计数的最高有效位的从 0 开始的索引吗?
  • 只需将您的掩码创建为mask = ((1&lt;&lt;n)-1) &lt;&lt; p,然后用 x 异或。

标签: c gcc bitwise-operators bit-shift bitwise-xor


【解决方案1】:

不,不正确。

x &gt;&gt; (p+1-n) 将移动所有原始数字的位,因此最高有效位不能保持不变。

我会使用类似下面的东西

unsigned invert(unsigned x, int p, int n)
{
    int const n_bits = sizeof(x) * CHAR_BIT;
    assert(p >= 0  &&  p < n_bits);
    assert(n >= 0  &&  n + p <= n_bits);
    if ( n == 0 )
        return x;
    unsigned const mask = (~0u >> (n_bits - n)) << p;

    return x ^ mask;
}

【讨论】:

  • (x &amp; ~mask) | (~x &amp; mask) 是x ^ mask。
  • 虽然断言n + p &lt; sizeof(x) * CHAR_BIT,调用者可以请求更改从位置0开始的所有位。
  • @EricPostpischil 1) 是的,我的错。谢天谢地optimizers 现在原谅了很多。 2) 另一个好点。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-02-11
  • 2021-12-30
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多