c - 返回 x,其中从位置 p 开始的 n 位设置为 y 的最右边 n 位,其他位保持不变

标签 c implementation bit-manipulation

我的解决方案

get the rightmost n bits of y
a = ~(~0 << n) & y

clean the n bits of x beginning from p
c = ( ~0 << p | ~(~0 << (p-n+1))) & x

set the cleaned n bits to the n rightmost bits of y
c | (a << (p-n+1))

这是相当长的陈述。我们有更好的吗?

 i.e
x = 0 1 1 1 0 1 1 0 1 1 1 0
p = 4
y = 0 1 0 1 1 0 1 0 1 0 
n = 3

the 3 rightmost bits of y is 0 1 0 
it will replace x from bits 4 to bits 2 which is 1 1 1

最佳答案

我写过类似的:

 unsigned setbits (unsigned x, int p, int n, unsigned y)
{
  return (x & ~(~(~0<<n)<<(p+1-n)))|((y & ~(~0<<n))<<(p+1-n));
}

关于c - 返回 x,其中从位置 p 开始的 n 位设置为 y 的最右边 n 位,其他位保持不变,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6727351/

相关文章:

c++ - 在两个以上的位上使用按位与

c - 如何释放C中二叉树中分配的内存

c - 实时图表中自动缩放 y 轴

c - 需要帮助 : Stack using a pointer in C

java - 该算法是否已正确实现?

java - 为什么这个加法代码(使用按位运算)在 java 中有效

c++ - 了解负数并转换它们

c - 为什么 Ackermann 函数在这个用 C 语言编写的 Mouse 解释器中需要这么长时间?

c - 执行 lex 的窗口无法识别 ./a.out

java - 将大型 XML 文档从一种格式转换为另一种格式的最快、最好的方法