This is demonstration sample code of the atoi() function in MIPS assembler. Launch EzMIPS, copy the following MIPS code and paste it into EzMIPS. Assemble, Run.
.data
szGoodNum: .asciiz "123"
szBadNum: .asciiz "12a"
szError: .ascii "This string does not represent "
.asciiz "a decimal integer\n"
szIntegerIs: .asciiz "- The integer number is: "
# -------------------- code section -------------------------- #
.text
la $s1, szGoodNum # save string address into $s1
# change this to szBadNum to test
li $t0, 10
li $t2, 48 # 48 = '0'
li $t3, 57 # 57 = '9'
# ........................... atoi() ......................... #
atoi:
lbu $t1, ($s1) # load unsigned char from string
beq $t1, $zero, print # is it a NULL terminator?
blt $t1, $t2, err # is it < '0' ?
bgt $t1, $t3, err # is it > '9' ?
addi $t1, $t1, -48 # convert $t1's ascii value to decimal
mul $s2, $s2, $t0 # int_val *= 10
add $s2, $s2, $t1 # int_val += array[s1] - '0'
addi $s1, $s1, 1 # $s1 is next char's address
j atoi # go get next char
# ....................... print error ........................ #
err:
la $a0, szError # address of szError string
li $v0, 4 # print string
syscall
j end
# ....................... print integer ...................... #
print:
la $a0, szIntegerIs # address of szIntegerIs string
li $v0, 4 # print string
syscall
move $a0, $s2
li $v0, 1 # print integer
syscall
# ......................... end .............................. #
end:
li $v0, 10
syscall
# ------------------------------------------------------------ #
Please let me know of any suggestions or bugs regarding the code above.
Regards,
Antonis