tags:

views:

154

answers:

4

This is my assembly program which is just a function to swap *x *y. So first argument from main is address of x which is in 8(%ebp) and second one is address of y is in 12(%ebp). The program does swap x and y. I need 7 lines for doing this. can you make it 6 lines and there is a condition you can use only %eax, %ecx, and %edx 3 registers. I think about it so much, but I can't make it 6 lines. There must be a way, isn't it? This might be not a big deal, but if there is a way to get it in 6lines I want to know.

movl 8(%ebp), %eax
movl (%eax), %ecx
movl 12(%ebp), %edx
movl (%edx), %eax
movl %ecx, (%edx)
movl 8(%ebp), %ecx
movl %eax, (%ecx)
+1  A: 

Maybe you can use the xor swap trick:

http://en.wikipedia.org/wiki/Xor_swap

Andreas Brinck
+1  A: 

What assembler are you using, and what processor are you targeting?

If you are using MASM, then you can add an offset to a register like this:

mov eax, ebp - 12
mov ecx, ebp - 8
mov ebp - 12, ecx
mov ebp - 8, eax

Alternatively, you can use the xchg instruction and do it in 3 lines:

mov eax, ebp - 12
xchg ebp - 8, eax
xchg ebp - 12, eax

This seems so simple that maybe i am missing something?

slugster
I think pointers to the values are on the stack, rather than the values themselves.
spong
The target is x86 and the assembler is gas, as I took the liberty to add in the tags.
Pascal Cuoq
`xchg` could indeed be useful for the stated metric of the number of instructions, but it is a little ridiculous to use this instruction in this context on a modern processor: this instruction implies a memory barrier.
Pascal Cuoq
+1  A: 

Motorola syntax isn't really my thing, but here is a shot at it in 5 instructions:

movl 8(%ebp), %eax
movl (%eax), %ecx
movl 12(%ebp), %edx
xchg (%edx), %ecx
movl %ecx, (%eax)

See Pascal's comment about shorter maybe being slower. The xchg %reg,(mem) is very likely to be slower than reloading addresses due to the implicit lock prefix.

spong
A: 

I got it!! it's based on xor swap trick. but something different^^; the answer is

movl 8(%ebp), %eax

movl (%eax), %ecx

movl 12(%ebp), %edx

xorl (%edx), %ecx

xorl %ecx, (%eax)

xorl %ecx, (%edx)

like this keep using one memory access. because in x86 source and destination both can not access the memories with an instruction. only one can be able to use in every single instruction. so I'm using like that.

kevin