Search code examples
pythonpython-3.xbit-manipulationbitwise-operatorsbitwise-and

Is there a way to reverse this python function?


def function(value):
    bit = value << 1 
    movebit = bit & 255 
    if (value> 127 ):
        movebit = movebit | 1
    return (movebit)

I have got this piece of code that I am trying to reverse so for example I know that the first line is actually to multiply the user_input and save it in bit.

the thing is I can not figure out how to change the next few lines to reverse the output.

example:

test = [226, 3, 214, 111, 20, 240]
# after function => [197, 6, 173, 222, 40, 225]
# goal is to reverse them back to test
toReverse = [197, 6, 173, 222, 40, 225]

my goal is to for loop over toReverse and on each element, send it to the function and get back the number that is on the same index as testArray.


Solution

  • It seem that function is rotl - rotate left operation. So reverse would be rotr: rotate right:

    def rotr(value):
        zbit = (value & 1) << 7
        return (value >> 1) | zbit