I'm writing a program in MIPS using Spim and I want to convert temperatures to/from fahrenheit and celsius. For example:
Enter a number to convert: 100
Enter the Temperature: C
100 C is the same as 212 F
So I'm having trouble getting the program to recognize if the user input a "C" or an "F" and jump to the appropriate label. Here's the part of the code I'm having trouble with:
li $v0, 8 # Loads System service to read string
syscall
move $s1, $v0 # Move value to register to save for later use
beq $s1, 'C', Fahrenheit
beq $s1, 'F', Celsius
The program just passes by the 'beq' lines without doing anything. Any help would be much appreciated!
Unlike reading integers, reading strings does not read the user input into register $v0
. A register in MIPS is only 4 bytes, so it doesn't make sense to store a string in a single register. Instead, MIPS will read it into memory starting at a specified address.
The read string syscall in MIPS works like this:
$a0
is the start address of the buffer in memory where the string is to be kept (you don't need to choose this yourself--you just allocate the space with a label name and MIPS will choose an address for you)$a1
is the length of the string buffer in bytes. For a single character you want this to be 2, because strings use their last byte as a null-terminator. If this is 1, the syscall won't even read anything from the user since that character automatically needs to be a null-terminator.You can allocate 2 bytes of memory for the string by including this in your .data
section
myString:
.space 2
Then perform the syscall in your .text
section:
li $v0, 8
la $a0, myString # myString is a label for the memory address
la $a1, 2
syscall
Then read the character (a single byte) you want into a register using lb
lb $s1, ($a0)
Your beq
instruction should work as you expect now.