2016-02-21 47 views
-3

我試圖用前面的2位交換二進制數中的最後兩位。在python中交換二進制位

E.g.我想0b11101011成爲0b11101110。

如何在python中使用按位運算符來實現?

謝謝。

+1

那你嘗試了嗎? –

+0

http://www.geeksforgeeks.org/swap-bits-in-a-given-number/ –

回答

2

一種方法是

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' 
3

正如你可以calcperm *看,它可以與bit_permute_step(又名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(或多個位,但答案是一樣的)

相關問題