|
| 1 | +#Shift-and-Add Multiplication |
| 2 | +.data |
| 3 | +multiplier: .word -7 |
| 4 | +multiplicand: .word 5 |
| 5 | +result: .word 0 |
| 6 | + |
| 7 | +.text |
| 8 | +la a0, multiplier # Load address of multiplier into a0 |
| 9 | +lw a1, 0(a0) # Load value of multiplier into a1 |
| 10 | +la a2, multiplicand # Load address of multiplicand into a2 |
| 11 | +lw a3, 0(a2) # Load value of multiplicand into a3 |
| 12 | +li t0, 0 # Initialize t0 to 0 (accumulator) |
| 13 | +li t1, 32 # Number of bits in a 32-bit architecture |
| 14 | + |
| 15 | +# Check the sign of the multiplier |
| 16 | +bltz a1, handle_negative1 |
| 17 | +j shift_and_add_loop |
| 18 | +# Check the sign of the multiplier |
| 19 | +bltz a3, handle_negative2 |
| 20 | +j shift_and_add_loop |
| 21 | + |
| 22 | +handle_negative1: |
| 23 | +neg a1, a1 # Negate multiplier if it is negative |
| 24 | +handle_negative2: |
| 25 | +neg a3, a3 # Negate multiplicand if it is negative |
| 26 | + |
| 27 | +shift_and_add_loop: |
| 28 | +beqz t1, end_shift_and_add # If t1 is zero, exit the loop |
| 29 | +andi t2, a1, 1 # Get the least significant bit of a1 |
| 30 | +beqz t2, skip_add # If t2 is 0, skip addition |
| 31 | +add t0, t0, a3 # Subtract multiplicand from the accumulator for negative result |
| 32 | + |
| 33 | +skip_add: |
| 34 | +srai a1, a1, 1 # Arithmetic right shift multiplier (divide by 2) |
| 35 | +slli a3, a3, 1 # Left shift multiplicand (multiply by 2) |
| 36 | +addi t1, t1, -1 # Decrement count |
| 37 | +j shift_and_add_loop |
| 38 | + |
| 39 | +end_shift_and_add: |
| 40 | +la a4, result # Load address of result into a4 |
| 41 | +sw t0, 0(a4) # Store result in memory |
| 42 | +# The result is now in memory at the address stored in a4 |
0 commit comments