title: How do I implement a division algorithm in ARM Assembly?
body: <p>I am trying to implement the following algorithm in ARM assembly, but when I run my code in ARMSim 1.9.1, it prints out the quotient and remainder completely unchanged (0 and 5 in this case). Can someone tell me what I am doing wrong? I think it is probably where I'm trying to set the rightmost bits of the register.</p>
  
  <pre><code>Given: Two positive integers: a Divisor X, and a Dividend Y
  Use three General Purpose Registers (R, Q, X)
  where R stores the Remainder, Q stores the Quotient, and X stores the Divisor. 
  Steps:
      1. Copy Y into the Remainder register (R)
         Register Q will be initialized as 0 
      2. update: R =  R - X
      3. If R &gt;= 0 then
          Shift the Quotient Register (Q) to the left (1 bit)
          and set the new rightmost bit to 1
         Else
          Restore the original value by of R:  R = R + X
              Also, Shift the Quotient Register (Q) to the left (1 bit)
              and set the new least significant bit to 0
      4. Shift the Divisor Register (X) to the right (1 bit)
      5. Repeat 31 more times
  </code></pre>
  
  <p>And here is my code:</p>
  
  <pre><code>.equ X, 12      @ the divisor - change to whatever number you wish
  .equ Y, 5       @ the dividend - change to whatever number you wish
  
  .global main
  
  main:   
          LDR R6, =Y              @ R6 = R = Y
          MOV R7, #0              @ R7 = Q = 0
          MOV R8, #0              @ R8 = count = 0
          LDR R9, =X              @ R9 = X
  loop:   SUB R6, R6, R9          @ R -= X
          CMP R6, #0              @ if R &gt;= 0
          BGE _if                 @ goto _if
          CMP R6, #0              @ else if R &lt; 0
          BLT  _else              @ else goto _else
          ADD R8, R8, #01         @ count++
          MOV R9, R9, LSR #01     @ shift X right 1 bit
          CMP R8, #32             @ if count &lt;= 32
          BLE loop                @ continue looping
  
  _if:
          MOV R7, R7, LSL #01     @ shift Q left 1 bit
          ORR R7, R7, #01         @ set rightmost bit to 1
  
  _else:
          ADD R6, R6, R9          @ R += X
          MOV R7, R7, LSL #01     @ shift Q left 1 bit
          AND R7, R7, #2147483646 @ set rightmost bit to 0
  
  exit:
          MOV R1, R7      @ R1 = Q
          SWI 0x6B        @ cout &lt;&lt; R1
          MOV R1, R6      @ R1 = R
          SWI 0x6B        @ cout &lt;&lt; R1
          SWI 0x11        @ exit
  </code></pre>