为了它的乐趣,我试图将整个文本按位向右旋转。意思是,我希望每个字符的最后一位(lsb)最终成为下一个字符的第一位(msb),最后一个字符的最后一位成为第一个字符的第一位。这是我尝试过的;
def bitwise_text_rotate(text):
# make a list of ascii codes
characters = [ord(a) for a in text]
# save last character's right-most bit
carry_bit = characters[-1] & 1
# list of processed characters
output = []
for char in characters:
print "processing", char
last_bit = char & 1
char = char >> 1
mask = (carry_bit << 8) & 1
char = char & mask
print "appending", char
output.append(char)
carry_bit = last_bit
return "".join([chr(a) for a in output])
但它不起作用。我得到全零。我有什么想法可以做得更好,或者我在这里做错了什么?
答案 0 :(得分:1)
试试这个:
s = map(ord, text)
return ''.join(chr(((a&1)<<7) + (b>>1)) for a,b in zip(s[-1:] + s, s))
答案 1 :(得分:1)
这些行不正确:
mask = (carry_bit << 8) & 1
char = char & mask
使用:
mask = carry_bit << 7
char = char | mask