A useful exercise in understanding assembly language and its relation to machine language is to take a short assembly language program and translate it to machine language by hand.
The following program, countbits, counts the number of bits set to 1 in registers $4 and returns the result in register $6.
main: li $10, 32 # set up loop counter
li $6, 0 # clear output sum
main10: andi $12, $11, 1 # test current bit
beq $12, $0, main20 # skip count if not set
addi $6, $6, 1 # otherwise increment count
main20: srl $11, $11, 1 # shift input right
addi $10, $10, -1 # decrement count
bne $10, $0, main10 # continue until zero
li $2, 10 # Halt code
Translate this program to machine code by hand, explaining for each line how you worked out the machine instruction.
Although it might be tempting to simply let the SPIM assembler do this, the exercise is useful way of learning the MIPS instruction formats. Refer to Appendix B (Assemblers, Linkers and the SPIM simulator) of the text (4th Edition ) for descriptions of MIPS assembly language instructions and the corresponding machine codes.