x86 assembly occurrence of a character
Introduction
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.
Issue
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);
//implementation:
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
is_in_array:
;Insert your code there
main:
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
is_there
push yes
screendisplay:
call printf
mov eax, 0
leave
ret
Certainly this will not be enough .....
Solution
is_in_array:
;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
ret
Explanation
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
FinSi
ecx = ecx - 1
edi = edi + 1
EndWhile
eax = 0
//The condition that defines "setz"
Si ZF = 1 Alors
eax = 1
EndIf