title: x86 Assembly Programming, using movzx and movsx for variables properly
body: <p>I am working on homework assignment for assembly programming class. Here is the assignment </p>
  
  <blockquote>
    <p>Implement the following expression in assembly language:</p>
    
    <ul>
    <li>BX = -val1 + 20 – (val2 + val3)
    
    <ul>
    <li>Assume that val1, val2, and val3 are 8-bit integer variables</li>
    <li>Initialize val1 with 5, val2 with 8, and val3 with -4</li>
    <li>You are only allowed to use 16-bit registers to hold intermediate results, whenever needed.</li>
    <li>Use movzx, movsx or neg instructions whenever needed.</li>
    <li>Use the debugger to verify your answer.</li>
    </ul></li>
    </ul>
  </blockquote>
  
  <p>Here is my code:</p>
  
  <pre><code>.386
  .model flat,stdcall
  .stack 4096
  ExitProcess proto,dwExitCode:dword
  .data
  val1 sbyte 0        ;intialize val1
  val2 sbyte 0        ;intialize val2
  val3 sbyte 0        ;intialize val3
  result sword 0      ;intialize result
  .code
  main proc
  mov val1,5      ;val1 = 5
  mov val2,8      ;val2 = 8
  mov val3,-4     ;val3 = -4
  
  mov ax,0
  mov bx,0
  mov cx,0
  mov dx,0
  
  
  movzx dx,val1       ;dx = val1
  neg dx              ;dx = -val1
  add dx,20           ;dx = -val1 + 20
  
  movzx ax,val2       ;ax = val2
  neg ax              ;ax = -val2 
  movzx cx,val3       ;cx = val3
  add ax,cx           ;ax = -val2 + val3
  add dx,ax           ;dx = -val1 + 20 -val2 + val3
  
  mov result,dx       ;result = dx
  mov bx,dx           ;bx = result, = -val1 + 20 -val2 + val3 
  invoke ExitProcess,0
      main endp
  end main
  </code></pre>
  
  <p>But when i use debugger to check register and see the value of bx its not returning the correct integer value i want, and i believe i should use the movsx command somewhere in the code, but i am sure how to because the variables i declare are 8-bit and we are only allowed to use 16-bit immediate storage</p>