2014-10-08 25 views
0

编辑:我想通了。这是我使用的代码。Bitshift在Python中循环移位加密和解密

def bitshiftEncrypt(word): 
    newWord = "" 
    for i in word: 
     shift = '{:07b}'.format(ord(i)+1) 
     newShift = shift[1:] 
     newShift += shift[0] 
     newWord += chr(int(newShift,2)) 
    print(newWord) 

def bitshiftDecrypt(word): 
    newWord = "" 
    for i in word: 
     shift = '{:07b}'.format(ord(i)) 
     newShift = shift[len(str(shift))-1] 
     newShift += shift[:-1:1] 
     newWord += str(chr(int(newShift,2)-1)) 
    print(newWord) 

感谢您的帮助!

回答

0

bin()会给你最短的代表。这会以各种方式使你受到影响。

3>> bin(3) 
'0b11' 
3>> '{:07b}'.format(3) 
'0000011' 
+0

我很困惑。我使用bin()[2 ::]的方式切断了二进制的0b,所以我可以循环移位它。这不是最好的路线吗? – haincha 2014-10-09 00:00:24

+0

“!”有多少位有? “z”有多少位? – 2014-10-09 00:05:30

+0

0b100001 0b1111010 这可能是一个问题。 :我忽略了这一点。让我再看看我的代码。 所以,当我解密它时,它错了,因为有错误的位数。 – haincha 2014-10-09 00:08:16