【问题标题】:How to find string length using scasb in Assembly如何在 Assembly 中使用 scasb 查找字符串长度
【发布时间】:2017-04-08 09:47:38
【问题描述】:

我有一个字符串,并试图找到它的长度。我正在使用 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

【问题讨论】:

    标签: assembly x86 nasm strlen


    【解决方案1】:

    对于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]
    

    【讨论】:

      【解决方案2】:

      对于汇编时间常数字符串,汇编器可以将长度计算为一个常数整数:

      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
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-03-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多