#1
  1. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Mar 2009
    Posts
    53
    Rep Power
    18

    [Assembly] strlen function


    I was just messing around and wanted to write some code that I could write to a boot sector and boot from.

    I proceeded to study assembly(since thats what you have to use when it first boots up), and I have a little program that is supposed to write "Hello World!" to the screen, then wait for a key press, and then print "You may now shutdown you computer...".

    It works, but to print the string, you have to give it the length of the string. I wanted to be able to just give it the string and not have to deal with lengths, so I wrote a strlen function. Here it is:

    Code:
    ; SHOULD put the length of the string pointed to by bp in cx
    strlen:
    
    	push es				; Save the values of modified variables on the stack
    	push bx
    
    	mov bx,bp
    	mov es,bp			; Set es to the pointer
    
    strlen_loop:				; The loop sub
    
    	cmp byte[es:0],0x00		; If the next character is 0x00, then there are no more characters!
    		je strlen_end		; Jump to the end
    
    	inc cx				; Increment the length
    	inc bx				; Increment the string pointer
    	mov es,bx
    
    	jmp strlen_loop			; Repeat!
    
    strlen_end:				; the end sub
    
    	pop bx
    	pop es				; Restore modified variables
    
    	ret				; return
    Like I said, I'm new to assembly, so this seemed like the way to do it, but i'm not sure.

    I know my strings are NULL terminated, but it isn't getting the correct string length( it doesn't get stuck forever, but it gets WAY too long)

    I think the problem lies in the cmp byte[es:0],0x00 part, but I'm not sure.

    Am I doing this correctly?


    EDIT:

    by the way, I'm using the nasm assembler.
  2. #2
  3. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Mar 2009
    Posts
    53
    Rep Power
    18
    NEVERMIND!

    Just found out about "scasb". Took about 5 seconds after I heard about that, and I had a working string length function. lol here it is:

    Code:
    ; SHOULD put the length of the string pointed to by bp in cx
    strlen:
    	push ax
    
    	mov di,bp			; scasb scans the byte at byte[di], so we need to put the poitner there
    
    	xor cx,cx			; scasb stores the length in cx
    	not cx				; it decrements so we need to set it up first
    	cld				; clear the direction flag so we go forwards in the string
    	xor al,al			; scasb compares with al, so make al 0
    	repne scasb			; keep repeating scasb until the byte and al are equal (you find zero)
    
    	not cx				; It was counting down from 65535. So if it was 32 characters, it would be 65503, not = 32
    	dec cx				; We don't want to count the trailing 0x00
    
    	pop ax
    
    	ret

IMN logo majestic logo threadwatch logo seochat tools logo