Skip to content

Instantly share code, notes, and snippets.

@totzyuta
Created January 15, 2015 04:18
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save totzyuta/76ef4055ea4c03778e17 to your computer and use it in GitHub Desktop.
Save totzyuta/76ef4055ea4c03778e17 to your computer and use it in GitHub Desktop.
myprintf() function in c and assembly
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;
}
.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