如何在 Assembly 中使用 scasb 查找字符串长度

How to find string length using scasb in Assembly

我有一个字符串,正在尝试找出它的长度。我正在使用 rw32-2017。我尝试使用 repe scasb 扫描字符串,但它根本没有改变 ZF。 有没有更简单的方法来查找字符串的长度?

我的程序:

%include "rw32-2017.inc"

section .data
    ; write your data here
    string1 db "how long is this string",0

section .text
main:
    mov ebp, esp
    
    ; write your code here
    mov esi,string1
    mov eax,0
    mov ecx,50      ;max length of string is 50
    mov ebx,ecx
    cld
    repe scasb 
    sub ebx, ecx
    mov eax,ebx
    call WriteUInt8

    ret

对于SCAS,你应该把字符串的地址放在EDI,而不是ESI。而不是 REPE 你想要 REPNE (重复而不等于 ecx!=0)。

mov edi,string1
mov eax,0
mov ecx,50 ;max lenght of string is 50
mov ebx,ecx
cld
repne scasb   ; find AL (0), starting at [ES:EDI]

对于assemble-time-constant字符串,assembler可以将长度计算为常量整数:

string1 db "how long is this string",0
len equ $-string1       ; len = current position - start of string

len 提供长度,包括 0 字节。 (如果您只对字符串使用显式长度操作,例如 write 系统调用,或者至少使 0 不是长度的一部分,您可能希望省略终止字节 0你数)。

您可以将它用作立即数:

mov edx, len