【问题标题】:Translating Java code to ARM assembly?将 Java 代码转换为 ARM 程序集?
【发布时间】:2016-03-03 15:13:04
【问题描述】:

我想将一个计算从 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???

我是否正确翻译了 while 循环以及如何打印总和?抱歉,我对 arm 组件还很陌生,所以我不知道我是否做得对。

【问题讨论】:

  • 在调试器下运行,看看最终值是否符合您的预期。调试器可以代替乱扔打印代码(这在 asm 中真的很不方便)。
  • 好的,我看到 r1 等于 55,这是我所期望的,那么如何在将 r1 的值打印到标准输出时将其打印出来?
  • 根据您使用的操作系统,您可以调用 printf。查看 ARM 调用约定以找出 args 的放置位置。

标签: assembly while-loop arm


【解决方案1】:

while () 通常这样翻译:

_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???

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-10-13
    • 1970-01-01
    • 1970-01-01
    • 2017-06-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-30
    相关资源
    最近更新 更多