MIPS Palindrome Check -
i trying write mips programme checks if input string palindrome. tested string "helllleh" , when stepping through program, saw during first loop of pal_check t0 = 0 t1 = 104. logically, t0 = 0 , t1 = 0 in first loop. can tell what's wrong in program?
# a0 input # a1 current character looking @ # a2 length of string # t0 character @ origin of string # t1 character @ end of string # v0 stores whether string palindrome or not (0 false, 1 true) ispalindrome: addi $a2, $0, 0 # length counter find_len: lbu $a1, 0($a0) # load character $a1 beq $a1, $0, pal_check # break if string @ end addi $a2, $a2, 1 # increment counter addi $a0, $a0, 1 # increment str address j find_len pal_check: # palindrome if length less 2 slti $t0, $a2, 2 bne $t0, $0, return_true # check first , lastly chars see if same lbu $t0, 0($a0) # first char t0 add together $t1, $a2, $a0 # lastly char t1 lbu $t1, 0($t1) bne $t0, $t1, return_false # if not equal, homecoming false # go on recursion addi $a2, $a2, -2 addi $a0, $a0, 1 j pal_check return_false: addi $v0, $0, 0 jr $ra return_true: addi $v0, $0, 1 jr $ra
while finding length of string continually increment $a0
point @ next character, until find nul terminator @ end of string. never reset $a0
before palindrome check loop, it's still pointing @ nul terminator when begin loop. you'll comparing info that's past string.
it create more sense implement check way (i'm using c illustrate idea; i'll leave mips translation you):
a0 = the_string; a1 = the_string + strlen(the_string) - 1; while (a1 > a0) { if (*a0 != *a1) homecoming false; a0++; a1--; } homecoming true;
by way, terminology nitpick: # go on recursion
. implementation isn't recursive, it's iterative.
mips palindrome
No comments:
Post a Comment