Created
November 15, 2019 19:33
-
-
Save KaceCottam/37a065a2c194c0eb50b417cf67455af1 to your computer and use it in GitHub Desktop.
simple printf implemented in MIPS assembly architecture.
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
printf: # a0: address of format string | |
# a1, a2, a3: arguments 1, 2 and 3 | |
# example: printf("this is a format string with %d %s",int,string address) | |
# example: printf("this is another format string with %c %f\n",char,double address) | |
# %<indicator> will be replaced by the value of the argument. | |
addi $sp, $sp, -28 | |
sw $t0, ($sp) | |
sw $t1, 4($sp) | |
sw $t2, 8($sp) | |
sw $a0, 12($sp) | |
sw $a1, 16($sp) | |
sw $a2, 20($sp) | |
sw $a3, 24($sp) | |
la $t0, ($a0) # t0 is current start of string | |
addi $t1, $sp, 16 # t1 is the current argument | |
li $t2, 0 # t2 is the comparison handler | |
printf_loop0: # load at beginning of loop | |
lb $a0, ($t0) | |
beq $a0, $zero, printf_loop0_ | |
addi $t0, $t0, 1 | |
ori $t2, $zero, '%' | |
sub $t2, $a0, $t2 | |
beq $t2, $zero, printf_formatting | |
j printf_char_normal | |
nop | |
printf_formatting: | |
lb $a0, ($t0) | |
addi $t0, $t0, 1 | |
ori $t2, $zero, 's' | |
sub $t2, $a0, $t2 | |
beq $t2, $zero, printf_str | |
ori $t2, $zero, 'd' | |
sub $t2, $a0, $t2 | |
beq $t2, $zero, printf_int | |
ori $t2, $zero, 'f' | |
sub $t2, $a0, $t2 | |
beq $t2, $zero, printf_double | |
ori $t2, $zero, 'c' | |
sub $t2, $a0, $t2 | |
beq $t2, $zero, printf_char | |
# here there is an error | |
nop | |
printf_int: | |
li $v0, 1 | |
lw $a0, 0($t1) | |
addi $t1, $t1, 4 | |
j printf_call_ | |
nop | |
printf_str: | |
li $v0, 4 | |
lw $a0, 0($t1) | |
addi $t1, $t1, 4 | |
j printf_call_ | |
nop | |
printf_double: | |
li $v0, 3 | |
lw $t2, ($t1) | |
l.d $f12, ($t2) | |
addi $t1, $t1, 4 | |
j printf_call_ | |
nop | |
printf_char: | |
li $v0, 11 | |
lb $a0, 0($t1) | |
addi $t1, $t1, 4 | |
j printf_call_ | |
nop | |
printf_char_normal: | |
li $v0, 11 | |
j printf_call_ | |
printf_call_: | |
syscall | |
j printf_loop0 | |
nop | |
printf_loop0_: | |
lw $t0, ($sp) | |
lw $t1, 4($sp) | |
lw $t2, 8($sp) | |
lw $a0, 12($sp) | |
lw $a1, 16($sp) | |
lw $a2, 20($sp) | |
lw $a3, 24($sp) | |
addi $sp, $sp, 28 | |
jr $ra | |
nop |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment