Swapping+the+contents+of+two+areas+of+memory

//by Jon Ripley, August 2006//

The Windows API provides several functions for manipulating blocks of memory but is missing a function to swap the contents of two areas of memory.

This function can be added to your programs by adding following routine:

code format="bb4w" REM Call as: PROC_SwapMemory(addr1%, addr2%, size%) DEF PROC_SwapMemory(B%, D%, C%) PRIVATE memswap IF memswap=0 THEN LOCAL P%       DIM P% 10 [OPT 2 .memswap mov al, [ebx]   ; load AL from byte in B%        xchg al, [edx]   ; swap AL with byte at D%        mov [ebx], al    ; store AL in byte at B%        inc ebx          ; B%+=1 inc edx         ; D%+=1 loop memswap    ; C%-=1, if C% != 0 jump to memswap ret             ; return from the function ]     ENDIF CALL memswap ENDPROC code

To call this routine use the following code:

code format="bb4w" PROC_SwapMemory(addr1%, addr2%, size%) code Here **addr1%** and **addr2%** are the addresses of the two blocks of memory to be swapped and **size%** is the number of bytes to swap.

SYS SwapMemory
//This section is provided for advanced users and demonstrates techniques that may be of interest.//

To provide a similar interface to other Windows API functions memory management functions it may be desirable to rewrite the SwapMemory function to be called using SYS. To do this add this alternative code to your program:

code format="bb4w" DIM SwapMemory 27 P% = SwapMemory [OPT 2 ;entry sequence (using the _stdcall calling convention) push ebp          ; store the old base pointer mov ebp, esp      ; make the base pointer point to the current stack location ;                 ; which is where the parameters are mov ebx, [ebp+8]  ; load first parameter (addr1) mov edx, [ebp+12] ; load second parameter (addr2) mov ecx, [ebp+16] ; load third parameter (size) .mslp mov al,[ebx]      ; load AL from byte in addr1 xchg al,[edx]     ; swap AL with byte at addr2 mov [ebx],al      ; store AL in byte at addr1 inc ebx           ; addr1 += 1 inc edx           ; addr2 += 1 loop mslp         ; size -= 1, loop until size = 0 ;exit sequence mov esp, ebp      ; reset the stack pop ebp           ; restore the original base pointer ret 12            ; return from the function, clearing the stack ] code

To call this routine from BASIC use the following code:

code format="bb4w" SYS SwapMemory, addr1%, addr2%, size% code

Here **addr1%** and **addr2%** are the addresses of the two blocks of memory to be swapped and **size%** is the number of bytes to swap.

To call this routine from assembler use the following code:

code format="bb4w" push size% push addr2% push addr1% call SwapMemory code