For loop in x86 assembly and optimising code?

后端 未结 2 1321
时光取名叫无心
时光取名叫无心 2021-01-29 13:43

I am currently learning assembly programming as part of one of my university modules. I have a program written in C++ with inline x86 assembly which takes a string of 6 characte

相关标签:
2条回答
  • 2021-01-29 14:03

    I would suggest to look into assembly code which is generated by compiler. You can change and optimize it later.

    How do you get assembler output from C/C++ source in gcc?

    0 讨论(0)
  • 2021-01-29 14:25

    I can't help with optimization or the cryptography but i can show you a way to go about making a loop, if you look at the loop in this function:

    void f()
    {
            int a, b ;
    
            for(a = 10, b = 1; a != 0; --a)
            {
                b = b << 2 ;            
            }       
    }
    

    The loop is essentially:

            for(/*initialize*/; /*condition*/; /*modify*/)
            {
                // run code
            }
    

    So the function in assembly would look something along these lines:

    _f:
            push ebp
            mov ebp, esp
    
            sub esp, 8                 ; int a,b
    
    initialize:                        ; for
            mov dword ptr [ebp-4], 10  ; a = 10,
            mov dword ptr [ebp-8], 1   ; b = 1
    
            mov eax, [ebp-4]
    condition:      
            test eax, eax              ; tests if a == 0
            je exit
    
    runCode:
            mov eax, [ebp-8]
            shl eax, 2                 ; b = b << 2
            mov dword ptr [ebp-8], eax
    
    modify:
            mov eax, [ebp-4]
            sub eax, 1                 ; --a
            mov dword ptr [ebp-4], eax
            jmp condition
    
    exit:
            mov esp, ebp
            pop ebp
            ret
    

    Plus I show in the source how you make local variables;

    • subtract the space from the stack pointer.
    • and access them through the base pointer.

    I tried to make the source as generic intel x86 assembly syntax as i could so my apologies if anything needs changing for your specific environment i was more aiming to give a general idea about how to construct a loop in assembly then giving you something you can copy, paste and run.

    0 讨论(0)
提交回复
热议问题