views:

112

answers:

4

Assembly info: Using Visual Studio 2010 to write inline assembly embedded into C

Hello, I am trying to write into an array of chars in C and trying to mimic the action of this C code:

resNum[posNum3] = currNum3 + '0';

currently this is what i have:

mov ebx, posNum3; 
mov resNum[ebx], edx; //edx is currNum3
add resNum[ebx], 48; // add 48 because thats the value of the char '0'

I also tried doing this:

mov ebx, posNum3;
mov   eax, resNum[ebx] ;// eax points to the beggining of the string
mov eax, edx; // = currnum3
add eax, 48; // + '0'

No luck with any of this, help is more than appreciated!

A: 

My X86 asm is rusty, but... If you're using characters (8 bits) you need to first, before you start a loop, zero out EAX and then move the char into AH or AL, something like:

; Before you start your loop
xor EAX, EAX ; If you're sure you won't overflow an 8 bit number by adding 48, this can go outside the loop
; ... code here to setup loop
mov EBX, posNum3
mov AL, resNum[EBX]
add AL, 48
; ... rest of loop

Note that the compiler will do a better job of this than you will... Unless you're Mike Abrash or someone like him :)

JimR
A: 

Avoid using expressions like

mov resNum[ebx], edx;

because you never know what is resNum. It could be an expression like esp + 4, and there is no opcode for mov [esp + ebx + 4], edx, so use small steps instead.

Also, ebx is a register that have to be preserved across calls. See http://msdn.microsoft.com/en-us/library/k1a8ss06%28v=VS.71%29.aspx for details and learn about calling conventions.

ruslik
A: 

Most of inline assemblers allows using name instead of size ptr [name], so you can just write

mov al, currNum3
add al, 0x30 //'0'
mov edx, posNum3
mov ecx, resNum
mov byte ptr [edx+ecx], al

if resNum is a global array, not an function argument or local variable, you can write shorter code:

mov al, currNum3
add al, 0x30 //'0'
mov edx, posNum3
mov byte ptr [resNum+ecx], al
Abyx
+2  A: 

The problem is the instruction

mov resNum[ebx], edx

moves 4 bytes (an entire dword) into the destination, not a single byte. You probably want

mov byte ptr resNum[ebx], dl

instead. While the assembler will allow you to leave off the 'size ptr' prefix on the address, you probably don't want to, as getting it wrong leads to hard to see bugs.

Chris Dodd