在两个字节之间的给定点交换位 [英] Swapping bits at a given point between two bytes

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

问题描述

假设我有这两个数字:

x = 0xB7
y = 0xD9

它们的二进制表示形式是:

Their binary representations are:

x = 1011 0111
y = 1101 1001

现在我要在给定的点进行交叉(GA),例如从位置4开始.

Now I want to crossover (GA) at a given point, say from position 4 onwards.

预期结果应该是:

x = 1011 1001
y = 1101 0111

按位,该如何实现?

推荐答案

我只使用按位运算符:

t = (x & 0x0f)
x = (x & 0xf0) | (y & 0x0f)
y = (y & 0xf0) | t

这将适用于该特定情况.为了使其更具适应性,我将其放在一个函数中,例如:

That would work for that specific case. In order to make it more adaptable, I'd put it in a function, something like:

def swapBits (x, y, s, e):
    lookup = [255,127,63,31,15,7,3,1]
    mask = lookup[s] & !lookup[e]
    t = x & mask
    x = (x & !mask) | (y & mask)
    y = (y & !mask) | t
    return (x,y)

查找值使您可以指定要交换的位.让我们以 x xxxxxxxx 和y的 yyyyyyyy 以及2的起始位 s 和结束位 e 为6(在这种情况下,位数从左侧的零开始).

The lookup values allow you to specify which bits to swap. Let's take the values xxxxxxxx for x and yyyyyyyy for y along with start bit s of 2 and end bit e of 6 (bit numbers start at zero on the left in this scenario).

x        y        s e t        mask     !mask    execute
-------- -------- - - -------- -------- -------- -------
xxxxxxxx yyyyyyyy 2 6                   starting point
                              00111111  mask = lookup[2](00111111)
                              00111100       & !lookup[6](11111100)
                      00xxxx00          t = x & mask
xx0000xx                                x = x & !mask(11000011)
xxyyyyxx                                  | y & mask(00111100)
         yy0000yy                       y = y & !mask(11000011)
         yyxxxxyy                         | t(00xxxx00)

这篇关于在两个字节之间的给定点交换位的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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