pkucinski
pkucinski

Reputation: 75

Counting letter in Assembly

A few days ago I started learning assembly (32bit) and I have a question. I want to create a program which counting 'x' (only small letter) in text and shows it on the screen (this case -> 4). I wrote that but i am stuck. What have i to do in 'counting'?

Run

gcc -m32 program.s
./a.out

Output

4

My Code

 .intel_syntax noprefix
  .text
  .global main

main:
  mov eax, offset messg
  push eax
  call counting
  add esp , 4
  //print result
  push eax
  mov eax, offset printf_arg1
  push eax
  call printf
  add esp, 8
exit:
  //return from code
  mov eax, 0

  ret
counting:
// HERE

.data
messg:
  .asciz "x Exemple XText x"
printf_arg1:
  .asciz "%i"

Upvotes: 0

Views: 67

Answers (1)

Sep Roland
Sep Roland

Reputation: 39166

Next is a simple counting code.

; IN (address) OUT (eax=count) MOD (edx)
counting:
  mov  edx, [esp+4]         ; Address of the text is on the stack right above the return address
  xor  eax, eax             ; Clear the counter to be reported back
  jmp  .first               ; (*)
.test:
  cmp  byte ptr [edx], 'x'
  jne  .next
  inc  eax                  ; Found an 'x'
.next:
  inc  edx                  ; Move to the next string position
.first:
  cmp  byte ptr [edx], 0    ; Are we at the end of the string?
  jne  .test                ; No, go compare for 'x'
  ret

(*) You always need to first test for the end of the string, because a string could be empty!

Upvotes: 1

Related Questions