Accessing one character in a string

32,962

Looking at the documentation for the MARS syscall functions you can see that service 4, which you're using, expects $a0 to be "[the] address of null-terminated string to print", which explains the behavior you're seeing.

What you want is function 11 "print character", which prints the low-order byte as a character. In other words the following should work (not tested):

la $t0, string
lb $a0, ($t0)
li $v0, 11
syscall
Share:
32,962
darksky
Author by

darksky

C, C++, Linux, x86, Python Low latency systems Also: iOS (Objective-C, Cocoa Touch), Ruby, Ruby on Rails, Django, Flask, JavaScript, Java, Bash.

Updated on January 17, 2020

Comments

  • darksky
    darksky over 4 years

    I am using something like SPIMS or MARS with syscall functions.

    I am reading in a string (and it works because I can print it out) as follows:

    li $v0, 8
    la $a0, string
    li $a1, 256
    syscall
    

    However, I am having a problem accessing a single character of the string. So if I want to access the first character and print it, I am trying this:

    la $t0, string
    lb $a0, ($t0)
    li $v0, 4
    sys call
    

    If I try something like this:

    la $a0, string
    li $v0, 4
    syscall
    

    This prints out the whole string as string points to the whole string.

    If I try something like:

    la $a0, string
    lb $a0, ($t0)
    li $v0, 4
    syscall
    

    It gives me an out of bound error. I don't understand why though - isn't a character a byte long and this just loads the first byte from the string into $a0?

    Thank you

  • m0skit0
    m0skit0 over 12 years
    IMO you should always reset registers values before executing LI. You never know what the upper half-word might have.
  • markgz
    markgz over 12 years
    LI is a pseudo-op that the assembler usually expands into ORI $rd,$zero, low16bits followed by LUI $rd, hi16bits. The full 32 bits of the destination register are correctly set after a LI instruction, so there is no need to manually reset the register before a LI.