mips部门实施

时间:2011-12-26 20:39:34

标签: assembly mips division shift

我正在尝试在MIPS中实现一个除法算法,我应该这样做:

  1. 余数和商在同一个寄存器中,上半部分是余数,下半部分是商,该寄存器初始化为被除数的值。
  2. 将余数寄存器向左移位1位
  3. 然后仅从余数寄存器的余数部分中减去除数
  4. 检查rem是否小于0,如果rem< 0然后rem = rem + divisor,如果rem> 0,然后只将第一位(最低有效位为1)
  5. 继续这样做n次,其中n是除数的宽度,在我的情况下是6位宽,所以循环是6次
  6. 这是我到目前为止编写的代码,我首先尝试在正操作数上执行此操作,然后希望将其用于签名操作数

    # A program that divides two integers according to the approach described in Fig. 3.12
    
    .data   # Data declaration section
    
    .text
    
    main:       # Start of code section 
    li $s2, 4 # dividend, will als0 be used as the remainder register which will hold remainder and quotient initialized to dividend
    li $s3, 2 # divisor
    
    li $s4, 2 # another register to hold the dividend shifted 6 bits, for adding and subtracting dividend from remainder
    sll $s4, $s4, 6
    
    li $t0, 0 # counter of the loop
    
    LOOP:   sll $s2, $s2, 1 # shift the remainder regitser by 1 bit to right
    sub $s2, $s2, $s4 # subtract divisor from remainder part of the remainder register
    
    slt $t1, $s2, $zero # to check if rem < 0
    beq $t1, $zero, MORE # if rem no < 0 then branch to MORE label
    nop
    
    add $s2, $s2, $s4 # if rem < 0, to add the divisor to the remainder part of the remainder register
    
    j LOOP # jump back to the loop
    nop
    
    MORE:   # if rem > 0, then do arithmetic right shift and place 1 as the 0th position
    rol $s2, $s2, 1 # rotate the number to the left by 1 bit which is arithmetic right shift
    
    j LOOP # jump back to loop
    nop
    
    addi $t0, $t0, 1 # adding 1 to the counter of the loop
    slti $t1, $t0, 6 # checking if the loop condition is working or not
    bne $t1, $zero, LOOP
    nop
    
    add $a0, $zero, $s2 # putting the result in regitser a0
    
    li $v0, 1 # printing out the result
    syscall
    
    # END OF PROGRAM
    

    有人可以查看我的代码,告诉我哪里出错了。 感谢

1 个答案:

答案 0 :(得分:0)

参见this question并回答C中的参考代码。有符号整数的直接划分相当复杂。如果你很勇敢,请查看 Booth的分区算法