Saturday, January 5, 2008

工作笔试(二) Count the number of bits set in a 32-bit word

Answer to Ex2: Count the number of bits set in a 32-bit word

C code:

int counter=0;

for (i=0; i<32; i++) {
bit = input & (1< if (bit==1)
counter++;
}

MIPS code:
Assume: input is in $t0, counter is in $t1, bit is in $t2, i is in $t3

Addi $t5, $zero, 1 ;$t5 holds constant 1
Addi $t3, $zero, 32 ;$t3 is the loop index

Loop Sllv $t4, $t5, $t3 ;$t4=1< And $t2, $t0, $t4 ;$t2=input & (1< Beq $t2, $zero, Label ;is $t2 0?
Addi $t1, $t1, 1 ;$t1++
Label addi $t3, $t3, -1 ;decrement $t3
Bne $t3, $zero, Loop

0 comments: