Search code examples
assemblymipsmultiplicationbit-shift

Multiplication by a power of 2 using Logical shifts in MIPS assembly


Can someone please give me pointers on how I can go about making a code that multiplies using shifts in MIPS assembly? I don't understand how having a number 2^n can help me multiply using an odd multiplicand


I currently have this code, I'm trying to make a calculator

.text

li  $v0, 4 
la  $a0, ask_1
syscall

li  $v0,5
syscall
move    $s1, $v0


li  $v0, 4
la  $a0, ask_2
syscall

li  $v0,5
syscall
move    $s2, $v0

#sll    $s2, $s2, 3     #$s2 * $s2^3 = result
srl $s2, $s2, 1

li  $v0, 1
la  $a0, ($s2)
syscall


.data

ask_1:  .asciiz     "Enter Multiplier\n"
ask_2:  .asciiz     "Enter Multiplicand\n"
result: .asciiz         "The Answer is:\n"

Solution

  • Shifting a number n bits left multiples the number by 2n. For example n << 3 = n*2³ = n*8. The corresponding instruction is

    SLL $s1, $s2, 3       # $s1 = $s2 * 8   shift left by 3 bit-positions
    

    To multiply any number you can split the number into sums of power of 2s. For example:

    • n*10 = n*8 + n*2 = (n << 3) + (n << 1)

        SLL $t1, $s2, 1
        SLL $t2, $s2, 3
        ADD $s2, $t1, $t2
      

    You can also use a subtraction if it's faster

    • n*15 = n*16 - n = (n << 4) - n

        SLL $t1, $s2, 4
        SUB $s1, $t1, $s2