Reputation: 21
The code below is an i86 assembly function that will be called in c, count(char *string, char c). I'm storing the string in %esi and the character in %ecx, I'm not sure how to tell the program to stop looping when the string is over(when bytes are 0) because the cmpl function doesn't allow me to do that (operand type mismatch). I'm not sure if I'm even storing the string correctly or iterating through the string correctly. Any help would be greatly appreciated
.globl count
.text
#first argument is string, second is char
count:
push %ebp #push old ebp to top of stack
movl %esp, %ebp #point ebp to same thing as esp, both pointing to old ebp
#saving live registers
push %esi
push %edi
push %ebx
#take values from stack
movl $0, %eax #set count(eax) to 0
movl 12(%ebp), %ecx #move letter to be counted to ecx
movl 8(%ebp), %esi #move string to esi
lettercheck:
cmpl %esi, %ecx #compare current letter to ecx(letter to be counted)
incl %esi #next letter
je inccount #if match inccount
cmpl %esi, $0 #if no match and end of string
je end
jmp lettercheck #if not end of string and no match
inccount:
incl eax #inc count of char
cmpl %esi, $0 #check for end of string
jne lettercheck #if match and not EOS lettercheck
jmp end #else jmp end
end:
pop %ebx
pop %edi
pop %esi
movl %ebp, %esp
pop %ebp
ret
Upvotes: 1
Views: 2029
Reputation: 126195
%esi
holds a pointer, so you want to compare the byte it points at to the bottom byte of %ecx, not compare the pointer. So your comparison instruction should be
cmpb (%esi), %cl
The b
mean byte instead of longword, and the parens mean the value in memory pointed at by the register, rather than the register. To check for the end of the string, you want
cmpb $0, (%esi)
for all the same reasons, plus the fact that an immediate can only be the first operand to a comparison.
Upvotes: 1