2010-10-24 138 views
8

所以我有以下彙編語言代碼,我需要轉換成C.我困惑了幾行代碼。彙編語言到C

我知道這是一個for循環。我在每一行添加了我的評論。

我覺得for循環是這樣

for (int i = 1; i > 0; i << what?) { 
    //Calculate result 
} 

什麼是測試條件?我該如何改變它?

看看彙編代碼,變量'n'做什麼?

這是英特爾的x86所以格式是MOVL =源,什特

movl 8(%ebp), %esi  //Get x 
    movl 12(%ebp), %ebx //Get n 
    movl $-1, %edi   //This should be result 
    movl $1, %edx   //The i of the loop 
.L2: 
    movl %edx, %eax 
    andl %esi, %eax 
    xorl %eax, %edi  //result = result^(i & x) 
    movl %ebx, %ecx  //Why do we do this? As we never use $%ebx or %ecx again 
    sall %cl, %edx   //Where did %cl come from? 
    testl %edx, %edx  //Tests if i != what? - condition of the for loop 
    jne .L2    //Loop again 
    movl %edi, %eax  //Otherwise return result. 
+1

testl%edx,%edx檢查edx是否爲0,然後jne - 如果不爲零則跳轉。 – 2010-10-24 12:20:38

+0

你對哪條線感到困惑?在C中,for循環用於(;;){} – 2010-10-24 12:33:23

+0

爲什麼要將legacy asm轉換爲C? – 2010-10-24 12:34:33

回答

14

sall %cl, %edx移位%EDX通過%cl位向左。 (%cl,僅供參考,爲%ecx的低字節。)後續testl測試該偏移是否歸零%edx。

jne被稱爲是因爲它經常用於比較的上下文中,在ASM中通常只是減法。標誌將根據差異設置;如果項目相等(因爲x - x == 0),ZF將被設置。英特爾語法中也稱爲jnz;我不確定GNU是否也允許這樣做。

總之,這三條指令轉化爲i <<= n; if (i != 0) goto L2;。這加上標籤似乎做了for循環。

for (i = 1; i != 0; i <<= n) { result ^= i & x; } 

或者,更正確地(但實現相同的目標),do ... while循環。

i = 1; 
do { result ^= i & x; i <<= n; } while (i != 0); 
+0

謝謝!這非常有幫助。 – Catie 2010-10-24 13:31:33