soda
soda

Reputation: 23

x86 assembly compare with null terminated array

I'm working on a function in assembly where I need to count the characters in a null terminated array. I'm using visual studio. The array was made in C++ and the memory address is passed to my assembly function. Problem is my loop isn't ending once I reach null (00). I have tried using test and cmp but it seems as though 4 bytes are being compared instead of 1 byte (size of the char).

My code:

_arraySize PROC              ;name of function

start:                  ;ebx holds address of the array
    push ebp            ;Save caller's frame pointer
    mov ebp, esp        ;establish this frame pointer
    xor eax, eax        ;eax = 0, array counter
    xor ecx, ecx        ;ecx = 0, offset counter

arrCount:                       ;Start of array counter loop

    ;test [ebx+eax], [ebx+eax]  ;array address + counter(char = 1 byte)
    mov ecx, [ebx + eax]        ;move element into ecx to be compared
    test ecx, ecx               ; will be zero when ecx = 0 (null)
    jz countDone
    inc eax                     ;Array Counter and offset counter
    jmp arrCount

countDone:

    pop ebp
    ret


_arraySize ENDP

How can I compare just 1 byte? I just thought of shifting the bytes I don't need but that seems like a waste of an instruction.

Upvotes: 1

Views: 4461

Answers (1)

wallyk
wallyk

Reputation: 57784

If you want to compare a single byte, use a single byte instruction:

mov  cl, [ebx + eax]        ;move element to be compared
test  cl, cl                ; will be zero when NUL

(Note that a zero character is ASCII NUL, not an ANSI NULL value.)

Upvotes: 1

Related Questions