2014-10-08 18 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