0 Replies - 1591 Views - Last Post: 24 April 2009 - 12:54 PM

#1 NickDMax   User is offline

  • Can grep dead trees!
  • member icon

Reputation: 2255
  • View blog
  • Posts: 9,245
  • Joined: 18-February 07

String Length (x86)

Posted 24 April 2009 - 12:54 PM

Description: push a pointer to your string, then call the function, eax will contain the length.Calculates the length of a zero terminated string. The function uses the cdecl calling convention so it can be used directly within C/C++
.386p
PUBLIC _strLen

MODEL flat, C
_TEXT	segment dword public use32 'CODE'

_strLen proc near   ; int strLen(char *str)
	push 	ebp                            
	mov 	ebp, esp                      
	push 	edi
	pushf
	; First we will put a pointer to our string in edi. This will let us use the scan string byte (scasb) instruction
	; which works by comparing al with 'byte [edi]' -- it will then inc or dec edi depending upon the direction flag
	; so we want to ensure we clear the direction flag.
	; To simplify the loop we can use repne -- however for each iteration in decreases ecx, so we will have to adjust ecx
	; to get the count. 
	mov 	edi, dword ptr [ebp+8]	; get our pointer from the stack
	xor 	ecx, ecx	;zero ecx
	not 	ecx			;set ecx to the max integer 0xFFFF FFFF
	xor 	al, al		;zero  al
	cld 				;clear the direction flag so we move along the string forwards
	repne	scasb		;scan string byte for byte [di] == al
	; now we need to adjust ecx -- lets think about this in 8bit for moment:
	; we started with 0xFF = 1111 1111 and we decreased by 1 for loop, so if loop 156 times then
	; 255-156 = 99 = 0110 0011, not 0110 0011 = 1001 1100, gives you 156. Tada!
	; however we have to remember that we don't really want to count the extra 0x00 char at the end
	; so we will subtract 1.
	not 	ecx
	dec 	ecx
	mov 	eax, ecx	;set our return value...
	popf
	pop 	edi
	pop 	ebp
	ret 
_strLen 	endp

_TEXT    ends

END



Is This A Good Question/Topic? 0
  • +

Page 1 of 1