簡體   English   中英

帶2個條件的while循環以匯編代碼

[英]while loop with 2 conditions to assembly code

我想像這樣轉換while循環:

i=0; 
while ( (s[i]!='t') && (i<=20) ) {
  d[i]=c[i];
  i++;
}

有2個條件的匯編代碼。 我怎樣才能做到這一點? 以下是同時存在1個條件的版本。

    #################################################
# lab3_3a.s                 #
# while loop    char!=ASCII 0           #
#################################################
    .text       
        .globl __start 
__start:            # execution starts here

    li $t1,0        # counter for string
    li $s0,'t'      # chararacter to end copy
while:  lbu $t0,string($t1) # load a character
    sb $t0,copy($t1)    # copy character
    beq $t0,$s0,end     # if character to end copy then exit loop
    addi $t1,$t1,1      # increment counter
    b while         # repeat while loop
end:    li $t2,0
    sb $t2,copy($t1)    # append end character to copied string
    la $a0,copy     # display copy
    li $v0,4    
    syscall
    li $v0,10       # exit
    syscall         
        .data
string:     .asciiz "Mary had a little lamb"
copy:       .space 80

多謝你們。

因此,您已經成功反轉了條件之一,並使用它跳出了循環。 您是否想到您可以對另一個做同樣的事情?

    li $t1,0        # counter for string
    li $s0,'t'      # chararacter to end copy
    li $s1,20       # count to end copy
while:  lbu $t0,string($t1) # load a character
    sb $t0,copy($t1)    # copy character
    beq $t0,$s0,end     # if character to end copy then exit loop
    bgt $t1,$s1,end     # if count exceeds limit then exit loop
    addi $t1,$t1,1      # increment counter
    b while         # repeat while loop
i=0; 
while ( (s[i]!='t') && (i<=20) ) {
  d[i]=c[i];
  i++;
}

如果將s定義為char s[20];將包含兩個錯誤char s[20]; ,首先(i<=20)將是太多。 在數組長度測試中使用<=非常不尋常,如果char s[21];可能仍然正確char s[21]; 是定義的,但是您在源代碼中有兩個不同的“幻數” 20和21。第二個錯誤是,即使您進行了正確的長度測試, (s[i]!='t')也將提前執行i驗證,因此在最后一個字符處,您將具有越界訪問權限。

無論如何,用C來編寫C的方式有點像“類似於匯編”的方式:

i=0;
while(true) {  // Your "b while" is doing this already
  if (20 < i) break;    // test length first, to avoid s[21] (out of bounds)
  if ('t' == s[i]) break; // test for "terminator" character
    //^^ Yoda notation, to catch typo like (s[i]='t') as error
  d[i]=c[i];
  ++i;  // pre-increment form is more accurate to your intent
        // As you don't need original value after incrementation
}
// breaks will jump here.

這應該很容易在匯編中重寫,請嘗試...


編輯:並且您的原始程序集不是“ while”,而是“ do-while”,即在所有情況下都將執行第一個字節的復制,這不是C示例正在執行的操作。


edit2:同時,這當然假設您知道布爾邏輯代數,就像每個程序員都必須知道的那樣。 即您知道:

!(A && B) <=> (!A) || (!B) 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM