MIPS统计二进制中1的个数代码故障排查求助
Fixing Your MIPS Code to Count Binary 1s
Let's break down the issues in your code that are causing unexpected behavior, then walk through a corrected version:
Key Problems in Your Original Code
1. Infinite Loop When $t0 Becomes 0
Your loop doesn't check if $t0 is already 0 before entering the AND block. Once $t0 gets shifted right to 0, the code will keep running andi $t2, $t0, 1 (which returns 0), shift $t0 again (still 0), and jump back to AND forever. We need an early exit check for when $t0 hits 0.
2. Incorrect Value Loading for Output
In the display section, la $a0, ($t1) is wrong—la loads memory addresses, but $t1 holds the counter's numeric value. To print the actual count, you need to move the value directly into $a0 with move $a0, $t1.
3. Redundant & Overcomplicated Code
- The line
la $t0, nwhen reading input is unnecessary:syscall 5stores the user's input in$v0, and you already copy it to$t0withmove $t0, $v0. - Initializing the counter by loading from the
.datasection is overkill. You can just useli $t1, 0to set it to 0 directly.
Corrected Code
# Count number of 1s in a 32 Bit Number # $t0 = user input # $t1 = counter .data prompt: .asciiz "Enter Number: " result: .asciiz "Number of 1s counted: " .text # Prompt User for Number li $v0, 4 la $a0, prompt syscall # Get user Input li $v0, 5 syscall move $t0, $v0 # Move input value from $v0 to $t0 # Initialize counter to 0 li $t1, 0 AND_LOOP: beqz $t0, display # Exit loop immediately if $t0 is 0 andi $t2, $t0, 1 # Check least significant bit beq $t2, 1, increment_counter # If LSB is 0, just shift right and continue srl $t0, $t0, 1 b AND_LOOP increment_counter: add $t1, $t1, 1 # Increment counter srl $t0, $t0, 1 # Shift right b AND_LOOP display: # Print result message li $v0, 4 la $a0, result syscall # Print the counter value move $a0, $t1 li $v0, 1 syscall # Exit program cleanly (good practice) li $v0, 10 syscall
Key Changes Explained
- Added
beqz $t0, displayat the start ofAND_LOOPto exit as soon as$t0becomes 0, eliminating the infinite loop. - Renamed labels for clarity (
AND→AND_LOOP,loop→increment_counter) to make the logic easier to follow. - Replaced the counter initialization with
li $t1, 0for simplicity and efficiency. - Fixed the output step with
move $a0, $t1to pass the counter value correctly to the print syscall. - Added an explicit exit syscall (
li $v0,10) to properly terminate the program instead of letting it run off the end of the code.
内容的提问来源于stack exchange,提问作者Ooka
相关产品推荐
相关产品推荐

