String Length Function in NASM

In certain situations when I want to print some string to stdout we need the length for the write syscall in linux. So we can’t always depend on the $-string macro, which is valid for a defined string.

We use the REPNE (REPeat while Not Equal) instruction which will loop as long as CX != 0. Along with REPNE we use SCASB (scan byte string). It compares the content of the accumulator (AL, AX, or EAX) against the current value pointed at by ES:[EDI]. In the end we calculate the difference between offsets of the scanned string (EDI) and the original string (EBX) to find the length.

push ebx
push ecx
mov ebx, edi
xor al, al
mov ecx, 0xffffffff
repne scasb ; REPeat while Not Equal [edi] != al
sub edi, ebx ; length = offset of (edi - ebx)
mov eax, edi
pop ebx
pop ecx



2 thoughts on “String Length Function in NASM

    • Thanks 🙂 That is the normal way in assembly and it contains a null byte, but I have tried to save lines plus no null bytes 😉

      Furthermore you can make it short to 16 bytes if you remove my registers saving it’s state.
      push,pop ebx
      push,pop ecx

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s