我正在开发一个程序,它从用户那里获取一个整数,然后输出它的二进制等价物中有多少个 1。所以首先我认为我需要将其转换为二进制,然后使用循环检查所有 32 位以找出有多少个 1。
我已经浏览了几个小时并尝试不同的方法来首先将整数转换为二进制。最好的方法是什么?有没有办法直接读取二进制寄存器值,或者我需要先转换它?这是迄今为止我拥有的所有代码。
.data
EnterInteger: .asciiz "Enter an integer: "
.text
# Print the first message
li $v0, 4
la $a0, EnterInteger
syscall
# Prompt the user to enter the first integer
li $v0, 5
syscall
# Store the first integer in $t0
move $t0, $v0
这是我到目前为止的代码,但它不起作用。当我输入 4673 时,我应该得到“4”,但我只得到“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, 0
main:
bgt $t3, 32, exit
andi $t0, $v0, 1
bne $t0, $zero, count
count:
addi $t3, $t3, 1
addi, $t1, $zero, 1
# Shift to the next bit and then go back to main
srl $t0, $t0, 1
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