Search code examples
assemblyx86masm

Using variable with register: error A2022: instruction operands must be the same size


I'm getting this error when I try to build this code:

1>------ Build started: Project: Project, Configuration: Debug Win32 ------
1>  Assembling [Inputs]...
1>assign2.asm(12): error A2022: instruction operands must be the same size
1>assign2.asm(13): error A2022: instruction operands must be the same size

It happens when I try to subtract ml1337skillz from usPop and store that result into Difference. I'm using eax as a temporary register for it.

TITLE Learning      (learning.asm)
INCLUDE Irvine32.inc

.data
usPop DWORD 313900000d               ; 32-bit
my1337Sk1LLz WORD 1337h              ; 16-bit
Difference SWORD ?                   ; 16-bit

.code
main PROC
 FillRegs:
    mov eax,usPop           ;load 3139000000d into eax    ; fine
    sub eax,my1337Sk1LLz    ;subtracts 1337h from usPop in eax  ; error #1
    mov Difference, eax     ;stores eax into Difference         ; error #2

    call DumpRegs           ;shows Registers

    exit                    ;exits
    main ENDP
END main

Solution

  • These two lines are your problem:

    sub eax,my1337Sk1LLz    ;subtracts 1337h from usPop in eax
    mov Difference, eax     ;stores eax into Difference
    

    eax is 32 bits, but both my1337Sk1LLz and Difference are 16 bits.

    There are two ways you might get around this:

    1. Changing the size of my1337Sk1LLz and Difference. Right now you have the types as WORD and SWORD, respectively. You can change those to DWORD and SDWORD to make them 32-bit.

    2. Zero-extending and truncating. You'll need another register. I'll use edx since you don't seem to be using it there. First, you'll need to sign-extend my1337Sk1LLz:

      movzx edx, my1337Sk1LLz  ; move, zero-extended, my1337Sk1LLz into EDX
      

      Then you can do the subtraction:

      sub eax, edx  ; they're the same size now so we can do this
      

      Then you can store the low word of eax into Difference, discarding the high word:

      mov Difference, ax