我正在学习MIPS汇编语言,并且我被要求编写一个执行以下操作的程序:
除了我显然需要使用移位操作和两个移位值之间的逻辑比较之外,我很遗憾。我的想法是编写一个循环,将输入整数的最低有效位放在临时寄存器中,将该值左移1,将输入整数右移1,然后重复该过程直到输入整数等于0我只是不确定如何"采取"一个数字...有人可以帮助我吗?
提前致谢:)
答案 0 :(得分:0)
我解决了它:
.data
int: .word 0
pleaseEnter: .asciiz "Please enter an integer: "
yourIntBin: .asciiz "Your integer in binary code is: "
yourIntBinRev: .asciiz "And now in reverse: "
nl: .asciiz "\n"
.text
main:
# ask the user for an integer
li $v0, 4
la $a0, pleaseEnter
syscall
# get the user's integer, store in int
li $v0, 5
syscall
sw $v0, int
# set up temporary reg's
li $t7, 31 # shamt is in t7
j loop1
loop1:
lw $t0, int # load int to t0
srlv $t1, $t0, $t7 # shift by counter
bnez $t1, exit1 # if the bit is 1, exit the loop
beqz $t7, exit1 # if the counter has reached 0 with no 1s in the int word, exit the loop
addi $t7, $t7, -1
j loop1
exit1: # now t7 is the number of bits that come before the msb
move $t4, $t7 # save that number for later
# tell the user what their number in binary is:
li $v0, 4
la $a0, nl
syscall
li $v0, 4
la $a0, yourIntBin
syscall
li $v0, 1
# prepare temp reg's
li $t6, 32 # set t6 to the maximum number of bits in a word
sub $t7, $t6, $t7 # make t7 the number of bits that come after the msb (from the right)
j loop2
loop2:
# print the current bit
move $a0, $t1
syscall
beq $t7, $t6, exit2 # if t7 is now 32, leave the loop
lw $t0, int # load the integer
sllv $t0, $t0, $t7 # shift left by counter
srl $t1, $t0, 31 # isolate the bit
addi $t7, $t7, 1 # increment shamt
j loop2
exit2:
li $v0, 4
la $a0, nl
syscall
la $a0, yourIntBinRev
syscall
# now it's time to print the binary code in reverse
addi $t6, $t6, -1 # get t6 to be 31
move $t7, $t4 # put t7's value after the first loop back in t7
li $t4, 0 # clear out t4 to save register space
li $v0, 1 # prepare to print integers ("bits")
li $t5, 0 # ensure t5 is 0
lw $t0, int # get the input integer to t0
loop3:
sub $t4, $t6, $t5 # get t4 to the desired shamt
sllv $t1, $t0, $t4 # shift left to eliminate unwanted bits from the left
srl $a0, $t1, 31 # same, but now for the 31 bits to the right of my desired bit
syscall # print that bit
beq $t5, $t7, exit3 # if the reversal is complete, leave the loop
addi $t4, $t4, 1 # add 1 to the shamt
addi $t5, $t5, 1 # add 1 to the counter
j loop3
exit3:
li $v0, 4
la $a0, nl
syscall
# end of execution
li $v0, 10
syscall