0

I have a function. the input would be a word, and every time each character will be added to the shifted value of the result.

def magic2(b):
res = 0
    for c in b:
       res = (res << 8) + ord(c)
       print(res)
return res

Because it uses shifts, I will lose some data. I wanna to decode/reverse this with exact letters of the input word.

For example, if input would be "saman", the output is result "495555797358" and step by step would be:

115
29537
7561581
1935764833
495555797358

How can I get back to the input word just with these outputs?

2
  • What do you mean by "because it uses shifts, I will lose some data"? If your characters are all Latin-1, shifting each one by 8 bits won't lose any data. If they are, you will lose bits, but only because you're shifting by only 8 bits instead of 21 or 32. Commented Apr 24, 2018 at 0:47
  • 1
    Meanwhile, what have you tried to decode this? If you need a hint, what happens if you use chr(n & 0xff) and n >> 8 in a loop, or n, c = divmod(n, 256) in a loop? That should get you close, but there's a bit of trickiness left for you to solve. Commented Apr 24, 2018 at 0:50

1 Answer 1

1

Consider what you're doing: for each character, you shift left by 8 bits, and then add on another 8 bits.1

So, how do you undo that? Well, for each character, you grab the rightmost 8 bits, then shift everything else right by 8 bits. How do you know when you're done? When shifting right by 8 bits leaves you with 0, you must have just gotten the leftmost character. So:

def unmagic2(n):
    while n > 0:
        c = chr(n & 0xff) # 0xff is (1 << 8) - 1
        n = n >> 8

Now you just have to figure out what to do with each c to get your original string back. It's not quite as trivial as you might at first think, because we're getting the leftmost character last, not first. But you should be able to figure it out from here.


1. If you're using the full gamut of Unicode, this is of course lossy, because you're shifting left by 8 bits and then adding on another 21 bits, so there's no way to reverse that. But I'll assume you're using Latin-1 strings here, or bytes—or Python 2 str.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.