uni

University stuff
git clone git://git.christosmarg.xyz/uni-assignments.git
Log | Files | Refs | README | LICENSE

lab6_ex4.asm (1655B)


      1 .eqv SYS_PRINT_WORD     1
      2 .eqv SYS_PRINT_STRING   4
      3 .eqv SYS_READ_WORD      5
      4 .eqv SYS_EXIT           10
      5 
      6 .data
      7         inputmsg:    .asciiz "Number (0-15): "
      8         bounderrstr: .asciiz "Number must be 0-15\n"
      9         binstr:      .asciiz "Binary: "
     10 
     11 .text
     12 .globl main
     13 
     14 main:
     15         li      $v0, SYS_PRINT_STRING
     16         la      $a0, inputmsg
     17         syscall
     18         
     19         li      $v0, SYS_READ_WORD
     20         syscall
     21         move    $t0, $v0
     22         
     23         # Bounds check
     24         blt     $t0, 0, bounderr
     25         bgt     $t0, 15, bounderr
     26         
     27         # Init loop counter, We're right shifting in reverse
     28         # because otherwise the binary number is going to
     29         # show reversed. We assign 3 to `s0` because the range
     30         # 0-15 is 4 bits and we'll go from 3 to 0 (4 iterations).
     31         # We DON'T start with `s0 = 4` because the last bit
     32         # will be eaten. 
     33         # For example if the number is 3 then
     34         #
     35         # (0011 >> 3) & 1 = 0000 & 1 = 0
     36         # (0011 >> 2) & 1 = 0000 & 1 = 0
     37         # (0011 >> 1) & 1 = 0001 & 1 = 1
     38         # (0011 >> 0) & 1 = 0011 & 1 = 1
     39         #
     40         # So the result is 0011 which is the binary form of 3
     41         li      $s0, 3
     42         
     43 binloop:
     44         srlv    $t1, $t0, $s0   # t1 = t0 >> s0
     45         andi    $t2, $t1, 1     # t2 = t1 & 1
     46         
     47         li      $v0, SYS_PRINT_WORD
     48         la      $a0, 0($t2)
     49         syscall
     50         
     51         beq     $s0, 0, exit
     52         addi    $s0, $s0, -1
     53         j       binloop
     54         
     55 bounderr:
     56         li      $v0, SYS_PRINT_STRING
     57         la      $a0, bounderrstr
     58         syscall
     59 
     60 exit:
     61         li      $v0, SYS_EXIT
     62         syscall