mipsspim

If/Else Statement on character strings from SPIM system calls


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!


Solution

  • 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:

    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.