【发布时间】:2011-07-17 23:00:28
【问题描述】:
我的解决方案
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
【问题讨论】:
-
“从位置 p 开始的 n 位”从
p变为p+n-1... 那么为什么p-n+1会出现在您的表达式中(两次)? -
整个操作包括两部分,我说的是从最右边开始:位[p-n+1,p]和位[0,p-n+1]。我们想改变第一部分的值,保持第二部分不变。
-
对,但是来自 [p-n+1,p] 的位是位置 p 的 n 位 结束,而不是 n 位 开始 正如你的问题所说,在位置 p。 (假设位“开始”从 0...)我认为您需要修复您的代码或解决您的问题...
-
从 p 开始,假设从左到右迭代比特字符串。是的,你是对的,我应该说得更清楚。
-
是的,我会像您在评论中所做的那样表述它:“从位 p-n+1 到位 p。”如果您说一个位字符串“从第 7 位开始,在第 5 位结束”,我敢打赌 50% 的程序员会对此措辞提出异议 :-)
标签: c implementation bit-manipulation