Assembly 有符号整数的除法
我想知道是否有人知道如何在MIPS中执行两个有符号整数之间的除法,而不使用内置的除法运算Assembly 有符号整数的除法,assembly,integer,mips,division,signed,Assembly,Integer,Mips,Division,Signed,我想知道是否有人知道如何在MIPS中执行两个有符号整数之间的除法,而不使用内置的除法运算 在问题说明中,我被告知除数寄存器、ALU和商寄存器都是32位宽,余数寄存器是64位。我建议有多种方法,简单快速,只使用乘法和减法 如果不允许乘法,那么似乎还有很多整数除法算法只使用移位、按位运算和加减运算,例如,第一次点击谷歌:想想你如何手动执行二进制除法: # a/b, where a=2011 and b=18 1101111 ←quotient ┌────────
在问题说明中,我被告知除数寄存器、ALU和商寄存器都是32位宽,余数寄存器是64位。我建议有多种方法,简单快速,只使用乘法和减法
如果不允许乘法,那么似乎还有很多整数除法算法只使用移位、按位运算和加减运算,例如,第一次点击谷歌:想想你如何手动执行二进制除法:
# a/b, where a=2011 and b=18
1101111 ←quotient
┌──────────── ↓
10010 │ 11111011011 a
-10010↓↓↓↓↓↓ -64b × 1
───────↓↓↓↓↓
11010↓↓↓↓↓
-10010↓↓↓↓↓ -32b × 1
───────↓↓↓↓
10001↓↓↓↓
-00000↓↓↓↓ -16b × 0
───────↓↓↓
100011↓↓↓
-10010↓↓↓ -8b × 1
───────↓↓
100010↓↓
-10010↓↓ -4b × 1
───────↓
100001↓
-10010↓ -2b × 1
───────
11111
-10010 -1b × 1
──────
1101 remainder
这个“小学”长除法算法可以写成(用Python——我让你把它转换成MIPS)如下:
def无符号除法(被除数、除数):
如果除数==0:
引发零错误()
如果股息<除数:
返回0
#确定商的第一个数字的位置
移位量=被除数.位长度()-除数.位长度()
#循环以查找商的每一位
商=0
当换档量>=0时:
#计算商的一位
如果股息>=(除数更多信息:除数寄存器、ALU和商寄存器均为32位宽,余数寄存器为64位。ALU和除数寄存器减半,余数向左移位。这将商寄存器与余数寄存器的右半部分结合起来。从外观上看,不允许乘法结婚
def unsigned_divide(dividend, divisor):
if divisor == 0:
raise ZeroDivisionError()
if dividend < divisor:
return 0
# Determine the position of the first digit of the quotient
shift_amt = dividend.bit_length() - divisor.bit_length()
# Loop to find each bit of the quotient
quotient = 0
while shift_amt >= 0:
# Calculate one bit of the quotient
if dividend >= (divisor << shift_amt):
# new bit is 1
dividend -= (divisor << shift_amt)
quotient |= (1 << shift_amt)
# Move to the next digit
shift_amt -= 1
return quotient
def signed_divide(dividend, divisor):
is_negative = (dividend < 0) ^ (divisor < 0)
abs_quotient = unsigned_divide(abs(dividend), abs(divisor))
return -abs_quotient if is_negative else abs_quotient