Programming
FASM: Get String Length (strlen) – Pure assembler code
by admin on Mar.20, 2011, under Programming
Getting the length of a string is very important for my projects, thus I was looking for different ways of implementing functions which would allow me to determine the length of a string via my FASM code. After doing some research I found two ways which worked fine for me.
The first way was to include the C-library and use its functions, strlen in this case:
import msvcrt,strlen,'strlen'
I later used it like that:
invoke strlen,myString
And EAX would hold the length of the string. Ok, so far so good.
Anyway, I was looking for a better way of getting its length, so I found a small procedure which would search a string for the null-terminator and later return its length.
Here’s the procedure:
; Will return the length of a null-terminated string ; The result will be written to ECX ; ; Usage: ; hello_tmp db "test",0 ; ... ; ccall strlen, hello_tmp proc strlen, strInput mov ecx,-1 mov al,0 mov edi,[strInput] cld repne scasb not ecx dec ecx ret endp
As stated in the comments already, the result will be written to ECX. If you would prefer using a different terminator, replace
mov al,0
With another char from the ASCII-table, like:
mov al,0x32
It’s a great way of getting the length of a string and it’s also faster than the standard C-libraries.