Search code examples
pythonbit-manipulationreverse-engineeringreversebit-shift

i cant understand this bit-manipulation python code


i see alot of code patterns in Reverse Engineering writeups and i don't understand it like this one (some_value >> 8) & 0xff can anyone explain it?


Solution

  • You don't need to understand things on a registers level. Just think of the int as an int.

    What happens when you take an int like, say, 0x12345678 and shift it right 8 bits?

    Well, let's see:

    >>> hex(0x12345678 >> 8)
    '0x123456'
    

    You've knocked off the two rightmost digits—that is, the rightmost byte—because a byte is 8 bits.

    Now what happens if you bitwise-and it with 0xff?

    >>> hex(0x123456 & 0xff)
    '0x56'
    

    You've knocked off everything except the two rightmost digits—that is, everything but the last byte—because 0xff is a byte full of 1 bits.

    Put it together:

    >>> hex((0x12345678 >> 8) & 0xff)
    '0x56'
    

    So you're getting the next to last byte.

    And you can extract each byte of an int this way:

    >>> hex((0x12345678 >> 0) & 0xff)
    '0x78'
    >>> hex((0x12345678 >> 8) & 0xff)
    '0x56'
    >>> hex((0x12345678 >> 16) & 0xff)
    '0x34'
    >>> hex((0x12345678 >> 24) & 0xff)
    '0x12'
    >>> hex((0x12345678 >> 32) & 0xff)
    '0x00'