Help with a MIPS Assembly language program that adds and subtracts numbers?

Jaebee's Avatar, Join Date: Feb 2010
Newbie Member
Hi all, I've been trying to write an MIPS Assembly language that outputs the results of the following: 16+4-8+2 but it seems like when I try to store more than the number 10 in a register that it will only put 10 in. For example, I want to put 16 in to register $t0 but when I run it in SPIM it only puts 10 in? I would appreciate any help. Here is the code I have so far for it:

.text
.globl main
main:
# Evaluate the expression.
# Put the final result in a0 to prepare for the syscall.
li $t0, $t0, 16
# Put 16 in a register
li $t1, $t1, 8
# Put 4 in a register
add $a0, $t0, $t1
# a0 = t0 + t1

li $t2, 8
# Put 8 in a register
li $t3, 2
# Put 2 in a register

add $a1, $t2, $t3
# a1 = t2 + t3

sub $a2, $a0, $a1
# a2 = a0 - a1

# Print the integer result in a0
li $v0, 1
# Load the system call number
first_sample_breakpoint:
nop

syscall

second_sample_breakpoint:
nop

# Print endl.
la $a2, endl
# Load the address of the string
li $v0, 4
# Load the system call number
syscall

# Return.
li $v0, 0
# Load return value in v0.
jr $ra
# Return.
.data
endl: .ascii "\n"
0
xpi0t0s's Avatar, Join Date: Aug 2004
Mentor
16 decimal is 0x10 in hexadecimal, are you sure the register really contains only 10 decimal and that you're not misreading hex output?
What does the register contain if you try to put 17 into it? 15? If you get 11 and 0F respectively, then you're looking at hexadecimal.
0
virxen's Avatar, Join Date: Nov 2009
Pro contributor
first of all your code is full with errors.
that's why you get wrong results.
see the correct code

Code:
.data
endl: .asciiz "\n" 

.text
.globl main
main:
# Evaluate the expression. 16+4-8+2
# Put the final result in a0 to prepare for the syscall.
li $t0, 16 # Put t0=16 in a register
li $t1, 4  # Put t1=4 in a register
add $a0, $t0, $t1 # a0 = t0 + t1=20

li $t2, 8 # Put t2=8 in a register
li $t3, 2 # Put t3=2 in a register

#add $a1, $t2, $t3 # a1 = t2 + t3=10

sub $a0, $a0, $t2 # a0 = a0 - t2=20-8=12
add $a0, $a0, $t3 # a0 = a0 + t3=14

# Print the integer result in a0
li $v0, 1 # Load the system call number
syscall

# Print endl.
la $a0, endl # Load the address of the string
li $v0, 4 # Load the system call number
syscall

# Return.  there is no need to use this since you don't have jumps far.
#li $v0, 0
# Load return value in v0.
#jr $ra
# Return.