title: Dividing in Assembly
body: <p>I am trying to define a calculator in C language based on the Linux command <code>dc</code> the structure of the program is not so important all you need to know that I get two numbers and I want to divide them when typing <code>/</code>. Therefore, I send this two numbers to an assembly function that makes the division (see code below). But this works for positive numbers only. </p>
  
  <p>When typing <code>999 3 /</code> it returns 333 which is correct but when typing <code>-999 3 /</code> I get the strange number 1431655432 and also when typing both negative numbers like <code>-999 -3 /</code> I get 0 every time for any two negative numbers.</p>
  
  <p>The code in assembly is:</p>
  
  <pre><code>section .text 
  global _div 
  
  _div: 
    push rbp            ; Save caller state 
    mov rbp, rsp 
  
    mov rax, rdi        ; Copy function args to registers: leftmost... 
    mov rbx, rsi        ; Next argument... 
  
    cqo
    idiv rbx            ; divide 2 arguments 
    mov [rbp-8], rax 
  
    pop rbp             ; Restore caller state 
  </code></pre>