I am currently working on an assignment where I need to write an assembly-language subroutine called "hexasc" that converts numbers in the range of 0 through 15 into a printable ASCII-coded character ('0' through '9', or 'A' through 'F', depending on the number). I am using the MARS simulator.
I have attempted to write the subroutine using basic assembly language instructions such as "li" and "move", but I am having trouble getting the desired output. Here is the code I have written so far:
hexasc: li $v0, 48 add $v0, $a0 jr $ra
I would greatly appreciate any help or guidance on how to correctly implement this subroutine. I am particularly struggling with converting the input numbers to their corresponding ASCII characters without using any registers such as s0-s7, gp, sp, fp, and ra.
This is what I have right now:
`# hexmain.asm
.text
main: li $a0,0 # change this to test different values
jal hexasc # call hexasc
nop # delay slot filler (just in case)
move $a0,$v0 # copy return value to argument register
li $v0,11 # syscall with v0 = 11 will print out
syscall # one byte from a0 to the Run I/O window
stop: j stop # stop after one run nop # delay slot filler (just in case)
hexasc: # You can write your own code for hexasc here`
Let's think about this for a moment.
Number Ascii (hex)
0 30
1 31
2 32
3 33
4 34
5 35
6 36
7 37
8 38
9 39
A 41
B 42
C 43
D 44
E 45
F 46
So we see a simple pattern: If our 4-bit number is greater than 0x39, add 0x37 to the digit. Otherwise, add 0x30. (You may need to do andi $a0,$a0,0x0F
to chop off everything beyond the lowest 4 bits.)
EDIT: I didn't really do a good job of explaining why we add 0x37 to the number if it's greater than 9.
0x0A + 0x37 = 0x41 (ascii code of 'A')
0x0B + 0x37 = 0x42 (ascii code of 'B')
etc.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.