2013-10-14 88 views
0

我發現這個代碼片斷,我相信將整數轉換爲十六進制。但是,我沒有遵循它。我添加了說明我相信正在發生的意見,但我不知道爲什麼這樣做。所以,假設我正確地注意到每一行都在做什麼,請有人向我解釋爲什麼這樣做?至於它如何以任何方式幫助轉換爲十六進制?MIPS彙編:從整數轉換爲十六進制

$ A0爲整數值

$ A1是它的結果應該是

 addi $t0, $0, 48  #set $t0 equal to 48 
     sb $t0, 0($a1)   #store $to (48) at location 0 in $a1 
     addi $t0, $0, 120  #set $t0 equal to 120 
     sb $t0, 1($a1)   #store $t0 (120) at location 1 in $a1 
     addi $t1, $a1, 9  #set $t1 = the address + 9 

LOOP: 

     andi $t0, $a0, 0xf #$t0 = 1 if $a0 and 0xf are the same (0xf = beginning of hex)? 

     slti $t2, $t0, 10  #if $t0 is less than 10, $t2 = 1, else 0 
     bne $t2, $0, DIGIT #if $t2 does not equal 0, branch to DIGIT 
     addi $t0, $t0, 48  #set $t0 equal to 48 
     addi $t0, $t0, 39  #set $t0 equal to 39 (why did we just write over the 48?) 
DIGIT: 

     sb $t0, 0($t1)  #set $t0 equal to whatever's in location 0 of $t1 

     srl $a0, $a0, 4  #shift right 4 bits 

     bne $a0, $0, LOOP  #if $a0 does not equal 0, branch to LOOP 
     addi $t1, $t1, -1  #set $t1 = $t1 - 1 

DONE: 

     jr $ra    #set the jump register back to $ra 
     nop 

回答

1
slti $t2, $t0, 10  #if $t0 is less than 10, $t2 = 1, else 0 
    bne $t2, $0, DIGIT #if $t2 does not equal 0, branch to DIGIT 
    addi $t0, $t0, 48  #set $t0 equal to 48 
    addi $t0, $t0, 39  #set $t0 equal to 39 (why did we just write over the 48?) 

MIPS的地址使用分支延遲槽,這意味着始終遵循分支指令的指令在分支採取(或未採取)之前執行。

所以這說的是「如果$ t0小於10(即在0..9範圍內),轉到DIGIT,但首先加48(ASCII'0'),無論$ t0的值如何。如果分支被採用,你現在已經從0..9轉換爲'0'..'9'。如果分支未被採用,$ t0原來在10..15的範圍內,現在將在58..63的範圍內,所以我們再添加39個以獲得範圍在97..102('a'..'f')的ASCII碼的值「。

+0

ohhh所以他將它轉換爲ASCII碼,然後ASCII碼進入每個單獨的數字? – user2869231

+0

類別。最終結果是一個字符串,它只是一個(ASCII)字符數組。 – Michael

+0

啊...我不知道十六進制是一個字符串。想象它是用不同格式編寫的數字。這絕對有幫助..謝謝! – user2869231