2.22 [20] <§§2.7, 2.8> Write a procedure, bcount, in MIPS assembly language. The bcount procedure takes a single argument, which is a pointer to a string in register $a0, and it returns a count of the total number of b characters in the string in register $v0 . You must use your bfind procedure in Exercise 2.36 in your implementation of bcount
文字列の長さを数える関数を書きなさい。
#include <stdio.h> #include <assert.h> #include <string.h> int bcount(const char *s); int bcount(const char *s) { int cnt; const char *p; assert(s!=NULL); cnt = 0; for(p=s;*p!='\0';p++){ cnt++; } assert(cnt >= 0); return cnt; } char *test_data[] = {"1", "02", "003", "abcdef", "", NULL}; int main(void) { int i; int golden; int ans; int err; err = 0; for(i=0;test_data[i]!=NULL;i++){ golden = strlen(test_data[i]); ans = bcount(test_data[i]); if(ans == golden) { printf("OK:%d\n", ans); } else { err++; printf("ERROR:data = %s, golden = %d, ans = %d\n", test_data[i], golden, ans); } } if(err!=0){ printf("ERROR %d found\n", err); } else { printf("ALL DATA PASSED\n"); } return 0; }
答え
bcount: lbu $2,0($4) b .L8 move $3,$0 .L10: addiu $4,$4,1 lbu $2,0($4) addiu $3,$3,1 .L8: bne $2,$0,.L10 move $2,$3 j $31 nop