How do I replace last characters with 0?

Viewed 34

I have got this so far:

mov esi,0                       
mov edi,LENGTHOF source - 2     
mov ecx,SIZEOF source
L1:;iterate a loop
    mov al,source[esi]  
    mov target[edi],al          
    inc esi                 
    dec edi                 
    loop L1

From next data

source BYTE "This is the source string",0
       BYTE 4 DUP('%')
target BYTE SIZEOF source DUP('#')
       BYTE 4 DUP('^')

I got this output:

gnirts ecruos eht si sihT#^^^^

The target string should not have those characters at the end. I think I need to find the byte that needs to be zero and set it. How do I do that?

1 Answers

Before

This is the source string0
%%%%
##########################
^^^^

After

This is the source string0
%%%0
gnirts ecruos eht si sihT#
^^^^
  • Because of mov ecx,SIZEOF source, the loop has one iteration too many! See how that 4th '%' was overwritten by 0.

  • LENGTHOF source tallies the characters and the terminating zero. LENGTHOF source - 1 will point at the offset where you need to write the new terminating zero in the target.

This is another version of the loop, one that avoids using the slow loop instruction:

    mov  ecx, LENGTHOF source - 1  ; destination offset
    xor  ebx, ebx                  ; source offset
    mov  al, 0                     ; terminating zero
L1: mov  target[ecx], al
    dec  ecx
    mov  al, source[ebx]    
    inc  ebx
    test al, al                    ; until we reach terminator
    jnz  L1
Related