Created
January 15, 2015 04:18
-
-
Save totzyuta/76ef4055ea4c03778e17 to your computer and use it in GitHub Desktop.
myprintf() function in c and assembly
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
void print_char(char c) { | |
char s[2]; | |
s[0] = c; | |
s[1] = '\0'; | |
print_string(s) | |
} | |
void myprintf(char *fmt, ...) { | |
int i, argc = 0; | |
char *s; | |
while (*fmt) { | |
if (*fmt == '%') { | |
fmt++; | |
argc++; | |
switch (*fmt) { | |
case '%': | |
// Process of %% | |
break; | |
case 'c': | |
// Process of %c | |
break; | |
case 'd': | |
// Process of %d | |
i = *((int*) ((char *)&fmt + argc * sizeof(void *)) ); | |
print_int(i); | |
break; | |
case 'u': | |
// Process of %u | |
break; | |
case 's': | |
// Process of %s | |
s = *((int*) ((char *)&fmt + argc * sizeof(void *)) ); | |
print_string(s); | |
break; | |
break; | |
} | |
}else { | |
// print a character as it is | |
print_char(*fmt); | |
} | |
fmt++; | |
} | |
} | |
int main() { | |
myprintf("I am %s, my age is %d", "Yuta Totsuka", 21); | |
return 0; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
.text | |
.align 2 | |
_print_int: | |
subu $sp, $sp, 24 | |
sw $ra, 20($sp) | |
li $v0, 1 # 1: print_int | |
syscall | |
lw $ra, 20($sp) | |
addu $sp, $sp, 24 | |
j $ra | |
_print_string: | |
subu $sp, $sp, 24 | |
sw $ra, 20($sp) | |
li $v0, 4 # 4: print_string | |
syscall | |
lw $ra, 20($sp) | |
addu $sp, $sp, 24 | |
j $ra |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment