Skip to content

Instantly share code, notes, and snippets.

@bitoffdev
Created October 25, 2017 17:06
Show Gist options
  • Save bitoffdev/df684232cc279656788ea5e977586122 to your computer and use it in GitHub Desktop.
Save bitoffdev/df684232cc279656788ea5e977586122 to your computer and use it in GitHub Desktop.
MIPS print a 32-bit register as binary
#
# FILE: print_binary.asm
# AUTHOR: Elliot Miller, 2017
#
###############################################################################
.data
newline_string: .asciiz "\n"
#
# Name: print_binary
# Description: takes an integer as input and prints as binary
#
# Arguments: a0: an integer
# Returns: none
# Destroys: s0,s1,s2,s3,a0,v0
#
.text
print_binary:
addi $sp, $sp, -8
sw $ra, 4($sp)
move $s0, $a0
addi $s1, $zero, 31 # constant shift amount
addi $s2, $zero, 0 # variable shift amount
addi $s3, $zero, 32 # exit condition
print_binary_loop:
beq $s2, $s3, print_binary_done
sllv $a0, $s0, $s2
srlv $a0, $a0, $s1
li $v0, 1 # PRINT_INT
syscall
addi $s2, $s2, 1
j print_binary_loop
print_binary_done:
li $v0, 4
la $a0, newline_string
syscall
lw $ra, 4($sp)
addi $sp, $sp, 8
jr $ra
#
# Name: main
# Description: main function
#
main:
# push return address onto the stack
addi $sp, $sp, -8
sw $ra, 4($sp)
# print a binary number
li $a0, -1 # full register
jal print_binary
# retrieve return address from the stack and exit
lw $ra, 4($sp)
addi $sp, $sp, 8
jr $ra
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment