Search code examples
assemblymipsmips32

Trouble with assembly code


So I have been learning assembly and working on a small project for class. Its a simple program that multiples two numbers without using the built in mult instruction. Instead it does so by shift adding. But I am having trouble making it display the result in the QtSpim console.

.text

main:

li $v0, 0
li $t0, 1
li $t1, 0
li $a0, 2
li $a1, 3

main_loop:

    beq $a1, $zero, main_end
    beq $a0, $zero, main_end

    and $t1, $t0, $a1
    beq $t1, 1, main_do_add
    beq $t1, 0, main_do_shift

    main_do_add:
        addu $v0, $v0, $a0

    main_do_shift:
        sll $a0, $a0, 1
        srl $a1, $a1, 1

    j main_loop

main_end:
    li $v0, 10

I am very new to assembly and this is first real piece of program. So I am not sure what I am doing wrong.


Solution

  • You simply forgot to print the value.

    Here's the corrected and annotated program. Note: I did not check your multiply logic, but the result was 6, so I'm guessing that's what you wanted.

    I recommend adding sidebar comments to almost every asm line so you can follow your logic and compare it against the instructions you use to implement it.

    Anyway, here's the code [please pardon the gratuitous style cleanup]:

        .text
    
    main:
    
        li      $v0,0
        li      $t0,1
        li      $t1,0
        li      $a0,2
        li      $a1,3
    
    main_loop:
    
        beq     $a1,$zero,main_end
        beq     $a0,$zero,main_end
    
        and     $t1,$t0,$a1
        beq     $t1,1,main_do_add
        beq     $t1,0,main_do_shift
    
    main_do_add:
        addu    $v0,$v0,$a0
    
    main_do_shift:
        sll     $a0,$a0,1
        srl     $a1,$a1,1
    
        j       main_loop
    
    main_end:
        # BUGFIX -- this was missing
        move    $a0,$v0                     # get result to argument register
        li      $v0,1                       # print integer
        syscall
    
        li      $v0,10                      # exit program
        syscall