NASM Forum > Programming with NASM

Swap using declared bytes

(1/1)

kazo0:
Hi everyone,

I am having trouble trying to "swap" some 'variables'.

As I am told to do, I declared A and B, A having the ascii 3 in it and B having ascii 7:

--- Code: ---        a db "3",0xA
        lena equ $-a

        b db "7",0xA
        lenb equ $-b

--- End code ---

I then push A and B onto the stack and call my swap subroutine, I need to pass by reference:

--- Code: ---       
        push b ;push the address of b onto the stack
        push a; push the address of a onto the stack

        call swap

--- End code ---

The next step is in swap where I am having problems, I don't understand how to actually swap the declared bytes of A and B. I try and take A and B off the stack and put them into eax and ebx which I do successfully but I get errors when I try and put eax and ebx into A and B. It says "invalid combination of opcodes and operands" I don't understand how to move from a register to a declared 'variable':

--- Code: ---       
        mov eax, [esp+8] ;move the address of b into eax
        mov ebx, [esp+4] ;move the address of a into ebx

        mov a, eax
        mov b, ebx

--- End code ---

Thanks!

Frank Kotler:
You were doing good... until:


--- Code: ---        mov a, eax
        mov b, ebx

--- End code ---

As you noted when you pushed 'em, the unadorned names "a" and "b" are the address of "a" and "b". What you're attempting is essentially moving eax to the number 5 - not the contents of the memory address [5]! Obviously not possible...


--- Code: ---        mov [a], eax
        mov [b], ebx

--- End code ---

... would be "legal", but not what you want to do. Your variables are actually two bytes long, the '3' and the linefeed. Moving the (four byte) address into one would clobber the other. What you want to do (if I understand it) is to move one byte of the "[contents]" from one variable to the other.... ( this would be "dereferencing" the variable that you've passed by "reference", I believe)


--- Code: ---mov cl, [eax] ; cl - one byte - has '3'
mov ch, [ebx] ; ch - one byte - has '7'
mov [ebx], cl
mov [eax], ch

--- End code ---

We could also employ the "xchg" instruction:


--- Code: ---mov cl, [eax]
xchg [ebx], cl
mov [eax], cl

--- End code ---

As I understand it, "xchg" with [memory] implies "lock". Probably faster to do it the naive way(?).

See if that gets you past the "sticking point". If not, we can discuss it further...

Best,
Frank

kazo0:
If I could hug you, I would.

I wrote:


--- Code: ---        mov cl, [eax]
        mov ch, [ebx]
        mov [a], cl
        mov [b], ch


--- End code ---

And it seems to work, I am printing a and b and they seemed to have swapped.

I just have to make another one that passes by value but it should not be a problem now,

Thank you very much!

Navigation

[0] Message Index

Go to full version