Convert String of ASCII digits to int in MIPS/Assembler

别来无恙 提交于 2019-12-01 13:29:33
sampath

mask the first four bits by anding the string with 0x0F like this below

andi $t0,$t0,0x0F # where $t0 contains the ascii digit .

now $t0 has the int of it.

Assumes that $s1 points to the beginning of a NULL-terminated string (i.e. to the most significant digit), $t0 contains 10, and $s2 contains 0:

lp:         
  lbu $t1, ($s1)       #load unsigned char from array into t1
  beq $t1, $0, FIN     #NULL terminator found
  blt $t1, 48, error   #check if char is not a digit (ascii<'0')
  bgt $t1, 57, error   #check if char is not a digit (ascii>'9')
  addi $t1, $t1, -48   #converts t1's ascii value to dec value
  mul $s2, $s2, $t0    #sum *= 10
  add $s2, $s2, $t1    #sum += array[s1]-'0'
  addi $s1, $s1, 1     #increment array address
  j lp                 #jump to start of loop

This has one mul less per iteration, and there's no need of knowing the length of the string before entering the loop.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!