x86 Assembly: String Length

Calculate the length of a string by iterating over each byte until you reach a NUL terminator (zero).

C

#include <stdio.h>

int strlen2(char *s) {
    int len = 0;

    // Copy pointer to avoid modifying the original
    char *s1 = s;

    // Track how many iterations are required to find '\0'
    while (s1++ && *s1 != '\0') {
        len++;
    }

    return len;
}

int main(int argc, char *argv[]) {
    char msg[] = "hello";
    int msg_len = strlen2(msg);
    print("Length of '%s' is %d\n", msg, msg_len);
    //
    // Length of 'hello' is 5
    //
}

16-bit (DOS)

org 100h
jmp start

msg: db "hello", 0

; Main program
start:
    push msg                ; Push buffer address to stack
    call strlen             ; Get length (result in AX)
                            ;     the answer is 5
    add sp, 2 * 1           ; Clean up stack use
    ret                     ; End program


; strlen - Compute the length of a string
; ------------------------------
;
; Arguments (Stack):
;   [1] = Address of buffer
;
; Return:
;   AX = Length of string
;
strlen:
    push bp                 ; Begin stack frame
    mov bp, sp

    push cx                 ; Save registers used
    push di
    
    mov cx, 0               ; String length counter
    mov ax, 0               ; We will scan for NUL terminator
    mov di, [bp + 2 * 2]    ; Read argument address from stack

    .scan:
        scasb               ; Compare AL with byte [DI++]
        je .return          ; -> Terminator found, stop
        ; NOTE: The terminator doesn't count toward
        ;       the total length of the string.
        inc cx              ; Increment string length counter 
        jmp .scan           ; -> Continue scanning

    .return:
        mov ax, cx          ; Return length of string

        pop di              ; Restore registers used
        pop cx

        mov sp, bp          ; End stack frame
        pop bp              
        ret