Monday, March 9, 2020

strlen() in MIPS

This is a sample MIPS assembler code to calculate string length aka strlen(). The user is prompt to enter a string which is stored in a buffer. The application counts the number of bytes of the buffer until a NULL byte is found. Full explanation in the comments.

Launch EzMIPS, copy the following MIPS code and paste it into EzMIPS. Assemble, Run.


# --------- Implementation of strlen() in MIPS ---------- #

.data

szBuffer:  .space 256
szTheSize: .asciiz "The size of the '"
szString:  .asciiz "' string is "

# ------------------------------------------------------- #

.text

# ....................................................... #

    # Prompt user to enter a string
    li $v0, 8
    la $a0, szBuffer    # $a0 = address of input buffer
    li $a1, 255         # $a1 = max. number of characters
    syscall             # Read it!

# ....................................................... #

    jal strlen          # call strlen() function
                        # $v0 holds string length!
    move $t1, $v0       # store string length in $t1

# ....................................................... #
    
    # print "The size of the '"
    la $a0, szTheSize   # address of string to be printed
    li $v0, 4
    syscall             # print it!

# ....................................................... #

    # print szBuffer which holds the string entered
    la $a0, szBuffer    # address of string to be printed
    li $v0, 4
    syscall             # print it!

# ....................................................... #

    # print "' string is "
    la $a0, szString    # address of string to be printed
    li $v0, 4
    syscall             # print it!

# ....................................................... #
    
    # print string length (integer) held by $t1
    move $a0, $t1       # $a0 = $t1 = string length
    li $v0, 1           # print integer
    syscall             # Do it!

# --------------------- exit program -------------------- #

    li $v0, 10
    syscall

# ---------------------- strlen() ----------------------- #

strlen:

    addi $v0, $zero, 0  # $v0 will keep string length
                        # Initialize to 0

next:
    lb $t1, 0($a0)      # read 1 byte from the buffer
    beq $t1, $zero, return  # is this a '\0' ?
    addi $a0, $a0, 1    # NO, it is not, address of next 
                        # byte = $a0 + 1
    addi $v0, $v0, 1    # length = length + 1
    j next              # go read next byte

return:
    jr $ra               # yes, it is a '\0',
                         # return to the caller

# ------------------------------------------------------- #


Please let me know of any suggestions or bugs regarding the code above.

Regards,

Antonis

No comments:

Post a Comment