Starting from:
$35

$29

Lab 5 Solution

1. C strlen() Function [20 points]
The string function, size_t strlen(const char *s) (found in the standard C library) counts and returns the size in bytes of its argument string s, not including a terminating null character.
Translate this C function, strlen() shown below, into a MIPS assembly function. Copy Lab5_1_incomple.s and complete this program.
int strlen(const char *str)
{
    int i;
    for ( i = 0; str[i] != '\0'; i++ )
        ; /* Nothing. Just count the numbers until the terminating null character */

    return ( i );
}
A character in a string can be read using lb (load byte) instruction. The format of the instruction is exactly same as that of lw instruction except the size of the unit of reading.
This example shows how to access str[i].
        # Assume i is stored in register $t6 and the address of the string is stored $a0
        
        add     $t0,    $a0,    $t6     # The size of a character in a string is 1 byte
        lb      $t1,    ($t0)           # Read a character at str[i]
Note that "read string" system call returns a string containing '\n' at the end of the string. Thus, '\n' is also counted in strlen().
Save your code as "Lab5_1.s" and run it in PCSpim.
Check-off Requirement: Show your solution to TA and demonstrate program execution in SPIM.

2. C atoi() Function [30 points]
Write an atoi() function in MIPS, which convert a string into an integer. This function is one of basic functions in the standard C library. This function returns an integer of the string represented in decimal.
The specification is:
int atoi (const char * str);
If the string contains other than digits, it returns the converted value of the substring from the beginning which contains digits only. For example, atoi("49ers") returns 49 and atoi("nothing?") returns 0. Note that '0' is equal to 48 and '9' is 57. Assume we enter non-negative numbers only.
The program receives a string from keyboard input, pass it to atoi() function, and prints the return value from the function on the console.
Save your code as "Lab5_2.s" and run it in PCSpim.
Check-off Requirement: Show your solution to TA and demonstrate program execution in SPIM.

3. String Reverse Function [30 points]
Write a string reverse function that takes a string as a parameter and reverses it. The function need not return a reversed string if it stores the result to the address of the parameter. You might need strlen() function to compute the length of a string.
The program receives a string from keyboard input, reverses it by calling a function, and prints the reversed string on the console.
Input a string: cobbler
Reversed string: relbboc
Save your code as "Lab5_3.s" and run it in PCSpim.
Check-off Requirement: Show your solution to TA and demonstrate program execution in SPIM.

Submission Requirement
Turn in three source files (Lab5_1.s, Lab5_2.s, and Lab5_3.s).

More products