Search code examples
pythonassemblysigned

movsx in python


I am trying to decompile asm code to python. I encountered the following line

movsx eax, byte ptr [edi] 

I am looking for a way to do signed extension of a byte in python. I am currently using bytearray to get the individual bytes. After getting the individual bytes I need to do a signed extension for each of them.


Solution

  • I use the following snippet:

    # sign extend b low bits in x
    # from "Bit Twiddling Hacks"
    def SIGNEXT(x, b):
      m = 1 << (b - 1)
      x = x & ((1 << b) - 1)
      return (x ^ m) - m
    

    In your case b will be 8. You can probably precalculate the masks for a bit of speedup.

    The referenced hack can be found here.