按位替换两个数字的位 [英] Bitwise replacing bits in two numbers

查看:59
本文介绍了按位替换两个数字的位的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很感兴趣如何使用按位运算将位间隔从数字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 = 00000000 Y = 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)

这篇关于按位替换两个数字的位的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆