assembly MIPS汇编中数字的位反转

sauutmhj  于 2022-11-13  发布在  其他
关注(0)|答案(1)|浏览(154)

我正在学习MIPS汇编语言,我被要求写一个程序,它做以下事情:
1.接受整数作为用户输入
1.将该整数打印为带符号的二进制数
1.反转该整数中的位
1.打印结果的反向数字(也是二进制)
除了需要使用移位操作和两个移位值之间的逻辑比较之外,我还非常困惑。我的想法是编写一个循环,将输入整数的最低有效位放在一个临时寄存器中,将该值左移1,将输入整数右移1,然后重复这个过程,直到输入的整数等于0。我只是不知道如何“取”一个数字的一位......有人能帮我吗?

w46czmvw

w46czmvw1#

我解开了它:

.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

相关问题