问题描述
我很感兴趣如何使用按位运算将位间隔从数字X交换到数字Y.
I'm interested how I can swap interval of bits from number X to number Y using bitwise operations.
例如,我有电话号码:
X = 00000000Y = 00111111
X = 00000000Y = 00111111
positionStart,positionEnd
positionStart, positionEnd
我想用相同位置的Y位替换X中的[positionStart,positionEnd]位.
And I want to replace [positionStart, positionEnd] bits in X with bits from Y at the same position.
推荐答案
如果有掩码 m
指示要移动或交换的位,则可以这样移动它们:
If you have a mask m
that indicates the bits that you want to move or swap, you could move them like this:
x = x ^ ((x ^ y) & m)
或像这样交换它们:
t = (x ^ y) & m
x ^= t
y ^= t
这可以解释为仅在设置了 m
的地方采用 x
和 y
之间的按位差异.然后对 x
进行XOR运算,从而翻转 x
中的位,其中 x
和 y
不同(并且 m
已设置),因此它将 x
的那些位更改为 y
的位.相同的情况适用于 y
.
This could be explained as taking the bitwise difference between x
and y
, only in places where m
is set. Then XORing x
with that flips the bits in x
where x
and y
are different (and m
is set) so it changes those bits of x
into bits of y
. The same thing applies to y
.
可能会像创建面具一样
m = (2 << end) - (1 << start)
这篇关于按位替换两个数字的位的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!