Search code examples
assemblyx86masmmovzero-extension

MASM Assembly move 8 bit register to the 16 bit register (ie. mov cx, ch)


I decided to learn an assembly programming language. I am using this 8086 tutorial. At the bottom the exercise is to find an error in some instructions and one of them is

mov cx, ch 

I found some similar question on SO on this topic explaining how to achieve it but now I'd like to know why this operation is forbidden?

Let's assume I have 10d = 00001010b in CH and want to put it to CL and simultaneously erase CH. mov cx, ch seems to do it because it shows 10d as 16bit 00000000 00001010 and puts it respectively to CH and CL (entire CX)

What is wrong with it and why does given tutorial ask to find an error in this expression?


Solution

  • The mov instruction is used to move between operands of the same size. What you want to is extend the 8-bit ch into the 16-bit cx. There are two instructions available for that purpose:

    movzx cx,ch  ; zero-extends ch into cx. the upper byte of cx will be filled with zeroes
    movsx cx,ch  ; sign-extends ch into cx. the upper byte of cx will be filled with the most significant bit of ch
    

    Another way of accomplishing the same thing in this particular case would be:

    shr cx,8  ; zero-extend
    sar cx,8  ; sign-extend