汇编MIPS如何逐位检查该值?
我正在创建一个程序,供用户输入一个整数,然后检查每个位并计算其二进制值中有多少个 1。因此,如果我输入 4673,我应该得到“4”作为输出,因为有 4 个。这是我下面的代码,由于某种原因我只得到“0”作为输出。我的猜测是我没有正确加载“andi”和“srl”的每一位。我一步步检查,当涉及到 andi 和 srl $t0 时,它的值永远不会为 1,所以我不能一点一点地移动?
.data
Msg: .asciiz "Enter an integer: "
.text
# Print the first message
li $v0, 4
la $a0, Msg
syscall
# Prompt the user to enter the first integer
li $v0, 5
syscall
# Store the first integer in $t0
move $t0, $v0
addi $t3, $zero, 1
main:
bgt $t3, 31, exit
addi $t3, $t3, 1
andi $t0, $v0, 1
srl $t0, $t0, 1
bne $t0, $zero, count
j main
count:
addi, $t1, $t1, 1
# Shift to the next bit and then go back to main
j main
exit:
# Tell the interpreter to get read to print an integer
li $v0, 1
add $a0, $zero, $t1
#Print the integer
syscall
# End the program
li $v0, 10
syscall
I am creating a program for a user to enter an integer and then check each bit and count how many 1's is in it's binary value. So if I input 4673 I should get "4" as an output because there is 4 ones. This is the code I have below, for some reason I am only getting "0" as an output. My guess is I am not properly loading each bit with the "andi" and "srl". I check it step by step and when it comes to andi and srl $t0 never holds a value of 1, so I must not be shifting bit by bit?
.data
Msg: .asciiz "Enter an integer: "
.text
# Print the first message
li $v0, 4
la $a0, Msg
syscall
# Prompt the user to enter the first integer
li $v0, 5
syscall
# Store the first integer in $t0
move $t0, $v0
addi $t3, $zero, 1
main:
bgt $t3, 31, exit
addi $t3, $t3, 1
andi $t0, $v0, 1
srl $t0, $t0, 1
bne $t0, $zero, count
j main
count:
addi, $t1, $t1, 1
# Shift to the next bit and then go back to main
j main
exit:
# Tell the interpreter to get read to print an integer
li $v0, 1
add $a0, $zero, $t1
#Print the integer
syscall
# End the program
li $v0, 10
syscall
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您的循环中有这条指令
andi $t0, $v0, 1
。但是$v0
在循环内永远不会改变,所以你总是得到相同的值。无论该值是 0 还是 1,下一行的srl
之后都将是 0。整个位计数循环可以用这样的东西代替:
请注意,有更有效的方法可以做到这一点,而根本不需要任何循环。请参阅如何计算数量32 位整数中的设置位?
You've got this instruction
andi $t0, $v0, 1
in your loop. But$v0
never changes within the loop, so you're always getting the same value. And regardless of whether that values was 0 or 1, it's going to be 0 after thesrl
on the following line.The whole bit-counting loop could be replaced by something like this:
Note that there are more efficient ways of doing this, without any loops at all. See How to count the number of set bits in a 32-bit integer?