2016-03-03 82 views
0

我想翻譯一個java代碼,計算從1到n的總和,以武裝大會,我想知道如果我正確翻譯它?將Java代碼翻譯成ARM程序集?

這裏是我的代碼Java代碼我正在翻譯:

int sum = 0 ; 
int num = 10; 
int count = 1 ; 
while (count <= num) 
{ 
    sum += count ; 
    count++ ; 
} 
System.out.println(sum); 

這裏是我的手臂彙編代碼至今:

MOV r1, #0  ;store sum 
    MOV r2, #10  ;number to count to 
    MOV r3, #1  ;starting count 

start_while:   ;start while loop 
    CMP r3, r2  ;while count is less than number 
    ADD r1, r1, r3 ;add count to sum 
    ADD r3, r3, #1 ;increment count 
    BNE start_while  ;end while loop 
    ;print sum??? 

我是正確的翻譯,同時循環,我該怎麼辦打印總和?對不起,我對手臂裝配相當新,所以我不知道我是否做得對。

+0

運行它,看看最終的價值是你所期望的。調試器可以用打印代替亂拋垃圾的代碼(這在asm中真的很不方便)。 –

+0

好的,我看到r1等於55,這是我所期望的,那麼如何打印r1的值到標準輸出呢? – KenS2016

+0

根據您所在的操作系統,您可以調用printf。查找ARM調用約定來找出在哪裏放置參數。 –

回答

0

而()通常被翻譯如下:

_start: 
if (!condition) jump to _end 
    ; do stuff inside the while loop 
    jump to _start 
_end: 

所以你的循環應該是這樣的:一個調試器下

MOV r1, #0  ;store sum 
    MOV r2, #10  ;number to count to 
    MOV r3, #1  ;starting count 

start_while:  ; start while loop 
    CMP r3, r2  ; jump below while block if while condition is 
    BGT end_while ; not true anymore ("<= 10" gets ">10") 
    ADD r1, r1, r3 ;add count to sum 
    ADD r3, r3, #1 ;increment count 
    B start_while  ;go on with loop (no condition here) 
end_while: 
    ;print sum???