How does MOVSX assembly instruction work?

Abundance picture Abundance · Oct 21, 2015 · Viewed 24.8k times · Source

How does the assembly instruction MOVSX work in this following example:

MOVSX ECX,BYTE PTR DS:[EDX]

In this case, here are the state of the registers:

ECX = 0000000F   
EDX = 0012FD9F 

From what I thought, it takes last bytes of [EDX] = 9F, moves it to ECX and then sign extends it to match 16 bits = 0000009F. However, the actual result is 00000016. Can someone help explain where I'm wrong?

Answer

cadaniluk picture cadaniluk · Oct 21, 2015

That's partially correct. However:

BYTE PTR DS:[EDX] obtains the byte located at the address held in EDX. This byte is copied to ECX into the least significant byte and the rest is filled with the sign of the byte.

For your unexpected result, this means that at the memory address1 0x12FD9F the byte 0x16 is located.


Notes:

  • the Segment Override Prefix DS: isn't necessary here. [EDX] automatically refers to DS.

1 "memory address" refers to either virtual or physical memory here