# count words in an array that have no more than 4 bits set .globl __start .data nums: .word 15, 1, 5, 0x57, 0x9A n: .word 5 .text __start: la $a0, nums lw $a1, n # countwords (nums, n) jal countwords move $a0,$v0 li $v0, 1 syscall #print result li $v0, 10 syscall #exit bitcount: # int bitcount(int) counts set bits in $a0 li $v0, 0 #bits = 0 bloop: beqz $a0, bdone # no more bits are set and $t0, $a0,1 # either 0 or 1 add $v0, $v0, $t0 # add the bit that is (possibly) set srl $a0, $a0, 1 # shift next bit into position 0 j bloop bdone: jr $ra # return, count of bits in $v0 countwords: # int countwords( int *a, int n) counts words with at most 4 bits set sub $sp,$sp,16 sw $ra, 12($sp) #save return address!!!! sw $s2, 8($sp) # save s registers before use sw $s1, 4($sp) sw $s0, 0($sp) # now initialize our use for them move $s0, $a0 # arrry pointer move $s1, $a1 # LOOP COUNTER n li $s2, 0 # count of words = 0 cloop: beqz $s1, cdone # while (n--) sub $s1,$s1,1 # bitcount(*array++) returning $v0 lw $a0, ($s0) # *array add $s0,$s0,4 # array++ point to next word (4bytes) jal bitcount bgt $v0,4, cskip # if (bitcount <= 4) add $s2,$s2,1 # wordcount++ cskip: j cloop cdone: move $v0, $s2 # return count of words lw $ra, 12($sp) lw $s2, 8($sp) lw $s1, 4($sp) lw $s0, 0($sp) add $sp,$sp,16 jr $ra # return, count qualifying words in $v0