计算字符串中的字母数

时间:2018-03-31 01:03:20

标签: assembly x86 nasm

.data 
str: .ascii "aasembly language is fun./0"
.equ len, (. - str)
counta: .int 0
countb: .int 0
countc: .int 0
countA: .int 0
countB: .int 0
countC: .int 0
lowera: .ascii "a"
lowerb: .ascii "b"
lowerc: .ascii "c"
uppera: .ascii "A"
upperb: .ascii "B"
upperc: .ascii "C"

.text
.globl _start
_start:

lea str, %esi
mov $0, %ecx
mov lowera, %al
mov lowerb, %bl
mov lowerc, %cl
mov uppera, %dl
mov upperb, %ah
mov upperc, %bh
forloop:
cmpb (%esi), %al
je doescounta
cmpb (%esi), %bl
je doescountb 
cmpb (%esi), %cl
je doescountc
cmpb (%esi), %dl
je doescountA
cmpb (%esi), %ah
je doescountB
cmpb (%esi), %bh
jne dontcount

doescountC: 
incl countC
jmp dontcount
doescountb: 
incl countb
jmp dontcount
doescountc: 
incl countc
jmp dontcount
doescountA: 
incl countA
jmp dontcount
doescountB: 
incl countB
jmp dontcount
doescounta: 
incl counta

dontcount:
incl %ecx
add $1, %esi
cmp $len, %ecx
jna forloop
mov counta, %eax
mov countA, %ebx
mov $1, %eax
mov $0, %ebx
int $0x80
.end

我试图计算字符串中的所有abc。它只适用于3个计数。如果我有3个以上,它只会扫描字符串的第一个字母。

1 个答案:

答案 0 :(得分:1)

mov $0, %ecx

mov lowerc, %cl

您正在同时使用%ecx注册2个不同的东西!

因为 %cl寄存器只是%ecx 的最低8位,所以将 lowerc 分配给%cl会破坏重置的计数器在%ecx 计数器从99开始,而不是从0开始,这是小型大写字母“c”的ASCII代码。

cmp $len, %ecx
jna forloop

因此,jna forloop永远不会跳回,因为%ecx已超过您将其与之比较的直接值。

一个简单的解决方案是编写mov lowerc, %cl而不是写mov lowerc, %dh

或者考虑与直接值进行比较:

cmpb $99, (%esi)   ;Compare with "c"
je doescountc