Reputation: 13758
For the fun of it, I am trying to bitwise rotate a whole text to right. Meaning, I want every character's last bit (lsb) end up being next character's first bit (msb) and last character's last bit to be first character's first bit. Here is what I have tried;
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])
But it doesn't work. I am getting all zeros. Any ideas how I could do this better, or what am I doing wrong here?
Upvotes: 0
Views: 235
Reputation: 177901
These lines are incorrect:
mask = (carry_bit << 8) & 1
char = char & mask
Use:
mask = carry_bit << 7
char = char | mask
Upvotes: 1
Reputation: 838696
Try this:
s = map(ord, text)
return ''.join(chr(((a&1)<<7) + (b>>1)) for a,b in zip(s[-1:] + s, s))
Upvotes: 1