按位替换两个数字的位

编程入门 行业动态 更新时间:2024-10-11 05:25:28
本文介绍了按位替换两个数字的位的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

更多推荐

按位替换两个数字的位

本文发布于:2023-11-30 07:54:35,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1649254.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:两个   数字

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!