使用gcc编译内联汇编时出错,“shl”

时间:2013-01-04 16:53:05

标签: c++ gcc assembly x86 inline-assembly

这是我尝试转换为gcc样式asm内联汇编代码的实际代码。

#include<iostream>
using namespace std;

int reverse(int num);

int main(){
    int num;
    cout << "enter number: ";
    cin >> num;
    cout << endl;
    cout << reverse(num);
    return 0;
}

int reverse(int num){
    if(num == 0 || num == 1){
        return num;
    }
    __asm
    {
        xor eax, eax
        xor ecx, ecx     
        mov ebx, num    
        clc             ; clear carry
not_found:
        inc ecx
        shl ebx, 1
        jnc not_found


        rcr eax, 1
        mov edx, ecx
again:
        shl ebx, 1
        rcr eax, 1
        inc ecx
        cmp ecx, 32
        jne again

        dec edx     
again2:     
        shr eax, 1
        dec edx
        cmp edx, 0
        jne again2
    }

}

由于我无法使用gcc编译上述代码,我尝试将其转换为可以由gcc编译器成功编译的东西,但到目前为止,我无法设法产生任何有意义的结果。

1 个答案:

答案 0 :(得分:0)

基于OP注释中的代码,这是一个使用内联汇编移位一位的修改示例:

#include<iostream>
using namespace std;
int reverse(int num);
int main()
{
    int num;
    cout << "enter number: ";
    cin >> num;
    cout << endl;
    cout << reverse(num) << endl;
    return 0;
}

int reverse(int num)
{
    if (num == 0 || num == 1)
    {
        return num;
    }
    int temp = 0;
    asm( "shll $1, %0 \n\t" : "=r"(temp) : "0"(num));
    return temp;
}

请注意,gcc如果您使用r约束请求操作数将操作数放入寄存器中,所以实际上没有理由mov自己(至少在这个小样本中)。 另外,我在输入约束中使用0来表示它应该与输出相同的寄存器,因为这就是shl的工作原理。

仍然不确定num == 1条件,但可能是因为我们不知道完整函数的实际功能。

相关问题