Computer Engineering Project Collection

-->

Sunday, February 01, 2009

MIPS - Bit counter

This is the second of the 3 problems of MIPS Assembly. The simulation, as before, using the MIPS32 Simulator called PC-SPIM. This is a free software that you can download and use for yourself. The problem basically is to count the number of bit '1' in a 32 bit integer number. This is the problem in detail :

Create a program that reads a 32 bit integer from memory and count the number of ones.
Again store the number of ones in memory.

The idea is to store the desired 32-bit integer number into the memory, load it into one of the registers, and then do some sort of 'manipulations'. The easiest is to do shift left logical (sll) on the number until the Least Significant Bit (LSB) become the Most Significant Bit (MSB), and the shift back that bit into LSB again using shift right logical. We use the shift right logical so that the more significant bits (that is the 'front' bits) filled with '0'.
Then we compare the resulting number with 0, if it's not the same as zero, then the counter adds 1. This process is repeated until all the bits checked.

Here is the code :

.data 0x10010000
.word 41210
.space 4
.text
.globl main
main: addu $s0,$ra,$0
lui $s1,0x1001
lw $s2, 0($s1)
addi $t0,$0,32
add $t1,$0,$0
loop: addi $t0,$t0,-1
beq $t0,$0,exit
sll $s3,$s2,$t0
srl $s3,$s3,31
beq $s3,$0,loop
addi $t1,$t1,1
j loop
exit: sw $t1,4($s1)
addu $ra,$0,$s0
jr $ra

Labels: , , , , ,

0 Comments:

Post a Comment

Subscribe to Post Comments [Atom]



<< Home