0

为了它的乐趣,我试图将整个文本按位向右旋转。意思是,我希望每个字符的最后一位(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])

但它不起作用。我得到了所有的零。有什么想法可以让我做得更好,或者我在这里做错了什么?

4

2 回答 2

1

试试这个:

s = map(ord, text)
return ''.join(chr(((a&1)<<7) + (b>>1)) for a,b in zip(s[-1:] + s, s))
于 2012-08-25T21:30:18.180 回答
1

这些行不正确:

mask = (carry_bit << 8) & 1
char = char & mask

采用:

mask = carry_bit << 7
char = char | mask
于 2012-08-25T21:38:29.987 回答