0

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"
Peter Cordes
  • 328,167
  • 45
  • 605
  • 847
pkucinski
  • 75
  • 5
  • 3
    I'd suggest looking for a simple (unoptimized) implementation of strchr, but instead of returning when you find a match, increment EAX counter. (And BTW, you can write `push offset messg`, no need to put the address into a register first.) Also, you're going to want `"%i\n"` as your format string for printf, with a newline. – Peter Cordes Jun 26 '21 at 13:50
  • (For future readers whose searching lands you here, if you're looking for optimized version, see [How to count character occurrences using SIMD](https://stackoverflow.com/q/54541129)) – Peter Cordes Jun 26 '21 at 13:52

1 Answers1

1

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!

Sep Roland
  • 33,889
  • 7
  • 43
  • 76