2016-03-21 74 views
2

我試圖模仿使用Jasmin的NOT門的行爲。的行爲如下:JVM中的邏輯NOT操作

  • 彈出堆棧
  • 如果整數爲0的整數,推1背面壓入堆棧
  • 別的推0背面壓入堆棧

我已經嘗試了兩次不同的嘗試,但無濟於事。

嘗試1:

...(other code1) 
    ifeq 3   ; if the top of stack is 0, jump 3 lines down to "i_const1" 
    i_const0  ; top of stack was not 0, so we push 0 
    goto 2   ; jump 2 lines down to first line of (other code2) 
    i_const1 
    ...(other code2) 

當然,上面的例子中不起作用,因爲需要ifeq <offset>在一個標籤,而不是硬編碼的整數作爲其偏移量。是否有類似於ifeq的操作確實接受整數作爲參數?

嘗試2:

... 
    ifeq Zero  ; top of stack is 0, so jump to Zero 
    i_const0  ; top of stack was 1 or greater, so we push 0 
    ... 
    ... (some code in between) 
    ... 
    ifeq Zero  ; top of stack is 0, so jump to Zero 
    i_const0  ; top of stack was 1 or greater, so we push 0 
    ... 
    Zero: 
    i_const1  ; top of stack was 0, so push 1 to stack 
    goto <???>  ; How do I know which "ifeq Zero" called this label? 

的問題,這是我在我的代碼已經不止一處利用非運算的。我嘗試使用標籤ifeq,但完成後我怎麼知道哪一行返回使用goto?有沒有辦法動態確定哪個「ifeq Zero」跳轉?

任何有識之士將不勝感激。

+3

取決於您的要求,如果您知道值爲0或1,則可以使用'x^1'。這避免了分支或標籤。 –

+0

@Peter Lawrey:......或者「1-x」。應該指出,問題代碼中的評論是錯誤的。要麼這個值是正好是一或零,那麼不爲零就意味着一個,不是「1或更大」,或者不是零也可能意味着小於零的值,所以它不能保證是「1或更大」。在任何一種情況下,「堆棧頂部爲1或更大」都是錯誤的... – Holger

回答

4

是否有類似的操作ifeq接受整數作爲參數?

是的,您可以使用$符號指定相對偏移量。
但是相對偏移量是以字節爲單位計算的,而不是以行爲單位。

ifeq $+7  ; 0: jump +7 bytecodes forward from this instruction 
    iconst_0  ; +3 
    goto $+4  ; +4 
    iconst_1  ; +7 
    # ...  ; +8 

有沒有辦法來動態確定「IFEQ零」作出跳躍?

編號使用多個不同的標籤而不是單個標籤Zero

那麼,實際上有一對支持動態返回地址的字節碼(jsr/ret)。但是這些字節碼是deprecated,並且在Java 6+類文件中不受支持。