uni

University stuff
git clone git://git.margiolis.net/uni.git
Log | Files | Refs | README | LICENSE

lab5_ex5.asm (1512B)


      1 .eqv SYS_PRINT_WORD     1
      2 .eqv SYS_EXIT           10
      3 .eqv SYS_READ_CHAR      12
      4 
      5 .macro isnotdigit(%ch, %lbl)
      6         # the character must be 0x30 <= c <= 0x39
      7         # for it to be a digit, otherwise, stop 
      8         blt     %ch, 0x30, %lbl
      9         bgt     %ch, 0x39, %lbl
     10 .end_macro
     11 
     12 .data
     13         # max word can be 10 digits long but à
     14         # we add + 1 byte in case there is '\n' 
     15         str: .space 11
     16 
     17 .text
     18 .globl main
     19 
     20 main:
     21         # init strlen/iterations counter
     22         li      $t1, 0
     23         
     24 getdigit:
     25         li      $v0, SYS_READ_CHAR
     26         syscall
     27         # copy $v0 to $t0
     28         addu    $t0, $v0, $zero
     29         isnotdigit($t0, atoi)
     30         # we don't read more than 10 digits
     31         beq     $t1, 10, atoi
     32         # save the digit in memory so that we can 
     33         # retrieve it later
     34         sb      $t0, str($t1)
     35         addi    $t1, $t1, 1
     36         j       getdigit
     37         
     38 atoi:
     39         li      $t0, 0
     40         # init sum
     41         li      $t3, 0
     42 
     43 atoiloop:
     44         lb      $t2, str($t0)
     45         # $t1 is the strlen of str so loop as
     46         # long as $t0 < $t1
     47         beq     $t0, $t1, exit
     48         # in case we hit '\n' or '\0'
     49         isnotdigit($t2, exit)
     50         
     51         # get decimal value
     52         addi    $t2, $t2, -0x30
     53         mul     $t3, $t3, 10
     54         add     $t3, $t3, $t2
     55         addi    $t0, $t0, 1
     56         j       atoiloop
     57 
     58 exit:
     59         li      $v0, SYS_PRINT_WORD
     60         la      $a0, 0($t3)
     61         syscall
     62         
     63         li      $v0, SYS_EXIT
     64         syscall