x86 assembly occurrence of a character

October 2016


The small assembly exercise below is for (Intel and AMD 32-bit) x86 architectures and uses the NASM syntax, an assembler, available for free and

that can be used on different platforms such as Windows or Linux.

Note that external functions used comes from the standard C library.


Imagine an array of characters (which does not necessarily end with 0). It has its size and we would like to test the presence of a given character

in this array. The aim will be to write a function that takes as input an array of characters, size and character. If this character is present in

the array, it returns a nonzero value, otherwise it returns zero.

Here are what give this function in C:

/the function
int is_in_array (char *array, int size, char c); 
char tab[] = {'n', 'e', 'u', 'e'};
is_in_array (tab, sizeof(tab), 'u'); //Return a value other than 0
is_in_array (tab, sizeof(tab), 'a'); //Return value 0

Simply insert your code in: 
extern printf

section .data
	array  db 'dadedidadedavivoufufifamasibifisaz'
	yes db 'oui', 10, 0
	no db 'non', 10, 0

section .text
	global main

	;Insert your code there

	push ebp
	mov ebp, esp
       ;Test if m is in the array 
	push dword 'm'
	;Lenght of array  (here 34) 
	push dword 34 
	;string address in eax
	push array

        ;Call is_in_array  with adress of array, 
        ;the size, and the value you are searching 
	call is_in_array  
	test eax, eax
	jnz is_there ;If eax != 0 display yes
	push no ;Then display no
	jmp screendisplay
        ;screendisplay of the string with printf
	push yes
	call printf

	mov eax, 0

Certainly this will not be enough .....


	;Retrieves the address of the array  (first parameter) in edi
	mov edi, [esp + 4] 
	;Retrieves the size of the array (second parameter) in  ecx
	mov ecx, [esp + 8]
	;Retrieves the character to find (third parameter) in eax
	mov eax, [esp + 12]

	;Search the character
	repne scasb
	;If flag ZERO (ZF) has a value of 1 it means character is found
	;In the other case it is not found
	;Simply add the value of ZF in eax
	mov eax, 0
	;If ZF = 1 then al = 1 (al being the 8 least significant bits of eax)
	setz al 



ZF = 0
ecx = length
eax = character
edi = array 
//The Loop that defines "repne scasb"
While ecx != 0 ET ZF = 0 Do
    if al == [edi] Then
        ZF = 1
    ecx = ecx - 1
    edi = edi + 1

eax = 0
//The condition that defines "setz"
Si ZF = 1 Alors
    eax = 1

Related :

This document entitled « x86 assembly occurrence of a character » from CCM (ccm.net) is made available under the Creative Commons license. You can copy, modify copies of this page, under the conditions stipulated by the license, as this note appears clearly.