将字符串转换为数字

问题描述 投票:0回答:1
# 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)正在摧毁原来的地址。

我该如何克服这个问题?

assembly mips
1个回答
1
投票

区分null和'0'没有问题。 null为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。在start_loop之前添加

   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
© www.soinside.com 2019 - 2024. All rights reserved.