交换 python 中的二进制位

Swap binary bits in python

我正在尝试将二进制数的最后两位与前两位交换。

例如我想让 0b11101011 变成 0b11101110.

如何在 python 中使用按位运算符实现这一点?

谢谢。

一种方法是

bin(a & ~15 | (a & 3) << 2 | (a & 12) >> 2)

# a & ~15          -- a with the last 4 bits cleared
# | (a & 3) << 2   -- or with the lowest 2 bits (0 & 1) shifted 2 steps to the left
# | (a & 12) >> 2  -- or with bits 2 and 3 shifted 2 steps to the right.

a = 0b11101011
bin(a & ~15 | (a & 3) << 2 | (a & 12) >> 2)
# '0b11101110'

正如你在 calcperm*, it can be done with a bit_permute_step (aka delta swap 中看到的那样,像这样

def bit_permute_step(x, m, shift):
    t = ((x >> shift) ^ x) & m
    x = (x ^ t) ^ (t << shift)
    return x

x = bit_permute_step(x, 3, 2)

..或类似的东西。如果我有任何错误,请纠正我的Python。

*:填写2 3 0 1 4 5 6(或更多位但答案相同)