0

Preconditions:
Addresses of 2 integer variables are on the stack as the parameters.

Sample c call:       swap( &num1, &num2);

You must implement the following C swap function:

/*
  Swaps the two values pointed to by x_ptr and y_ptr.
*/
void swap (int *x_ptr, int *y_ptr)
{
   if (x_ptr != y_ptr) 
   {
      *x_ptr ^= *y_ptr;  /* note that ^ means xor */
      *y_ptr ^= *x_ptr;
      *x_ptr ^= *y_ptr;
   }
}

Postconditions:
The values of the two integer parameters have been exchanged.

Edited by Nick Evan: Fixed formatting

4
Contributors
6
Replies
17
Views
6 Years
Discussion Span
Last Post by mohamed_101
0

swapping two integers in assembly is a lot easier than the code you posted. This assumes 32-bit integers on Intel family of 32-bit/64-bit processors

mov esi,x_ptr
mov eax,[esi]
mov edi,y_ptr
mov edx,[edi]
mov [esi],edx
mov [edi],eax
0

I was hoping to do this with the xor commands.
Also, at the end of this is the x pointer now pointing to what the y pointer was originally pointing to and vice versa?

0

I'm fairly new to Assembly myself, is there a reason something like this wouldn't work?

xchg eax, ebx ; swap Value1 and Value2
0

I'm fairly new to Assembly myself, is there a reason something like this wouldn't work?

xchg eax, ebx ; swap Value1 and Value2

That exchanges the two integers in the registers all right, but doesn't save the values in the memory addresses of the two pointers. The results still have to be saved at those addresses. But that xchg instruction isn't needed for the simple swap in this program -- wasted CPU time.

Edited by Ancient Dragon: n/a

0

Swap Two numbers using Stack in assembly language

.MODEL SMALL
.STACK 100H
.CODE
MAIN PROC
        MOV AX,'9'
        MOV BX,'4'
        PUSH AX
        PUSH BX
        POP  AX
        POP BX
        MOV DX,AX
        MOV AH,2
        INT 21H
        MOV DX,BX
        INT 21H
        MOV AH,4CH
        INT 21H
        MAIN ENDP
        END MAIN
This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.