代码之家  ›  专栏  ›  技术社区  ›  user366312

如何区分MIPS中的零和空值?

  •  0
  • user366312  · 技术社区  · 6 年前
    # replacing all digits in a string with their complement in 9.
    .data
        string: .asciiz "123471863"
    
    .text
    main:
        # load string's 1st address into the memory
        la $a0, string
    
        # initialize the loop-counter
        li $t0, 0
        li $t1, 9 # complement envelope for later use
    
        # start the loop    
    start_loop: 
        lb $t2, ($a0) # Take one character from string
    
        # loop termination condition
        beq $t2, $zero, end_loop # terminate if null-value found
    
        subi $t2, $t2, 48 # convert it to a digit
        sub $t2, $t1, $t2 # apply complement to $t2
        sw $t2,($a0) # restore the string-byte content
    
        addi $a0, $a0, 1 # go to next string-byte
        addi $t0, $t0, 1 # increment loop-counter
    
        j start_loop
    end_loop: 
    
        # print string  
        la $a0, string # load 1st address of the string
        li $v0, 4 # syscall for string print   
        syscall
    
        move $a0, $t0 # load 1st address of the string
        li $v0, 1 # syscall for string print   
        syscall
    
        # exit program
        li $v0, 10
        syscall
    

    程序没有按预期工作。在第一次迭代之后 $a0 寄存器没有给出正确的值。显然地, sw $t2,($a0) 正在销毁原始地址。

    我怎样才能克服这个问题?

    0 回复  |  直到 6 年前
        1
  •  1
  •   Alain Merigot    6 年前

    区分空值和“0”没有问题。空值为0,'\0'为48。

    你的测试

        beq $t2, $zero, end_loop # terminate if null-value found
    

    完全正确,将检测字符串的结尾。

    不正确的是你的算法。

    补足C中的一个数的方法是:

    while(c=*str){
      c=c-'0' ; // transform the number to integer
      c=9-c;    // complement it
      c += '0'; // add 48 to turn it back to a character
      str++;
    }
    

    您缺少最后一次字符转换。

    如果你改变

        sub $t2, $t1, $t2 # apply complement to $t2
    

        sub $t2, $t1, $t2 # apply complement to $t2
        addi $t2, $t2, 48
    

    一切都应该正常。

    或者,您可以简化算法并注意 c=9-(c-48)+48 相当于 c=105-c . 在开始循环之前添加

       li $t4 105 ## 
    

    换掉这三条线

        subi $t2, $t2, 48 # convert it to a digit
        sub $t2, $t1, $t2 # apply complement to $t2
        addi $t2, $t2, 48
    

    通过

       sub $t2,$t4,$t2  # complement to 9 directly on char representing the digit
    
    推荐文章