Bounty: +50 reputation points for anyone that provides the code to make this subroutine work with negative numbers.
I wrote a MIPS program to convert Fahrenheit to Celsius. It opens its own output window (i.e. UART) and properly displays the value in Celsius. It does all of this while making calls from C to assembly and vice versa. Entire code posted below.
I am struggling with getting it to work with negative numbers. Just drawing a blank right now for some reason. How do I change my itoa
function to write this check?
Anyone have any ideas how to get this working with negative values in MIPS?
.ent itoa
itoa:
// putting the stack frame together
addiu sp, sp, -16
sw fp, 12(sp)
move fp, sp
sw a0, 16(fp)
sw a1, 20(fp)
sw s0, 4(fp)
sw s1, 0(sp)
// there is no divide immediate, so using s1
li s1, 10
itoa_div_begin:
divu a0, s1
mfhi s0
mflo a0
addiu s0, s0, 0x30
addiu sp, sp, -1
sb s0, 0(sp)
beq a0, zero, itoa_div_done
nop
j itoa_div_begin
nop
itoa_div_done:
itoa_copy_begin:
lb s0, 0(sp)
sb s0, 0(a1)
addiu sp, sp, 1
subu s1, sp, fp
addiu a1, a1, 1
beq s1, zero, itoa_copy_done
nop
j itoa_copy_begin
nop
itoa_copy_done:
li s0, 0
sb s0, 0(a1)
move v0, a1
lw a0, 16(fp)
lw a1, 20(fp)
lw s0, 4(fp)
lw s1, 0(fp)
// stack frame
move sp, fp
lw fp, 12(sp)
addiu sp, sp, 16
jr ra
nop
.end itoa
The itoa() function coverts the integer n into a character string. The string is placed in the buffer passed, which must be large enough to hold the output. The radix values can be OCTAL, DECIMAL, or HEX.
The itoa (integer to ASCII) function is a widespread non-standard extension to the standard C programming language. It cannot be portably used, as it is not defined in any of the C language standards; however, compilers often provide it through the header <stdlib.
atoi is the 'ascii to integer' function and itoa is the reverse, the 'integer to ascii' function. You would use atoi to convert a string, say, “23557” to the actual integer 23557. Similarly, you would use itoa to convert an integer, say 44711, to the equivalent string “44711”. Very handy.
You can include this in your code, right above itoa_div_begin
:
li t0, 0x40000000
and t0, a0, t0
beqz t0, itoa_div_begin
nop
li t0, 45
sb t0, 0(a1)
addi a1, a1, 1
not a0, a0
addi a0, a0, 1
itoa_div_begin:
What is does:
-
in result, andIf you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With