tags:

views:

74

answers:

4

Hello, I'm trying to convert some c code to assmebly, and I need some help.

char encode(char plain){
    __asm{
        mov eax, plain
        add eax, 2      
        ret
    }
    //C code
    /*
    char code;
    code = plain+2;

    return code;*/
}

First problem is that visual studio complains that the register size doesn't match, i.e. eax is too small/large for char. I was under the impression that they were both DWORDs. Also, if I leave the variable in eax, and ret in assembly, it'll actually return that variable, right?

+1  A: 
  1. C chars are typically one byte, so try using AL instead of EAX (this refers to the lowest-order byte of the same register).
  2. Strictly speaking, the RET instruction simply pops the return address from the stack and transfers control there. The standard x86 calling convention does say that return values should be placed in EAX.
danben
+1  A: 

Yes, at least with most C compilers on x86 (though it's not theoretically guaranteed) whatever you put in [[e]a]x will be treated as a 1/2/4 byte return value.

No, char won't (normally) be a dword -- it'll be a byte.

char encode(char plaintext) { 
    __asm { 
        mov al, plaintext
        add al, 2
        leave
        ret
    }
}
Jerry Coffin
(Surely you meant `mov al, plaintext`?)
susmits
@susmits:Oops, yes. Thanks for pointing that out.
Jerry Coffin
+2  A: 

Remember, you can always look at the assembler output of a c file for hints on how to translate something. It's usually a single flag you have to enable.

Michael Dorgan
+1: this is an important point - you can save yourself a lot of pain when coding asm by using e.g. `gcc -S` to get some working template code to build upon
Paul R
A: 

A char is 8 bits, or one byte. Register eax is 32 bits, or 4 bytes, or two 16 bit words, or one 32 bit dword. And what is recognized as being returned depends on the compiler and code, but putting a value in eax will probably return that 32 bit value.

Fred