Reputation: 81
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)
Upvotes: 3
Views: 1249
Reputation: 81
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.
Upvotes: 1
Reputation: 14829
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.
Upvotes: 2
Reputation: 49984
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?
Upvotes: 3
Reputation: 52519
Maybe you can use the xor swap trick:
http://en.wikipedia.org/wiki/Xor_swap
Upvotes: 2