【问题标题】:How to compare two strings in x86 assembly with FASM?如何将 x86 程序集中的两个字符串与 FASM 进行比较?
【发布时间】:2017-11-18 12:37:33
【问题描述】:

我想将存储在寄存器si 中的用户输入与另一个字符串进行比较。
顺便说一句,我正在使用 FASM。这是用户输入后我的代码。
如果我使用repe cmpsb 命令,我知道我必须使用额外的段,但我不知道如何使用。而repe cmpsb 命令不适用于此代码。

.input_done:
   cmp si, 0
   je no_input
   jmp short .compare_input


.compare_input:
    mov cx, 20 ;For the repe cmpsb command.
    cld
    mov di, info ;The string I want to compare.
    mov es, di
    mov di, info
    repe cmpsb
    cmp cx, 0
    je showinfo
.showinfo:
    ... ;The output string if both string are the same.

info db "info", 0

【问题讨论】:

  • 您不仅需要指定汇编程序,还需要指定目标平台。例如,在 linux 中,这是完全错误的代码,因为它既没有使用 32b 也没有使用 64b 指针。那么如果你说这是 DOS 16b,我们需要看看你是如何定义数据的,为了你自己添加好问题,你应该尝试自己产生minimal reproducible example,例如你当前的代码确实设置了di两次,但不清楚si 中的内容(要么设置它,要么添加明确的评论)。
  • 这里有一篇文章解释了segment:offset 在 16b 实模式下的寻址(为了更好地了解,es 和 ds 的用途):thestarman.pcministry.com/asm/debug/Segments.html

标签: assembly x86 fasm


【解决方案1】:
mov di, info ;The string I want to compare.
mov es, di

对于一个简单的程序,这两个字符串可能确实会存储在同一个内存段中。只需将来自DS 的值放入ES。

...
push ds
pop  es
mov  di, info
...

而repe cmpsb 命令不适用于此代码。

您已将计数器 CX 设置为固定数字 20,其中至少有一个字符串(“info”)只有 4 个字符。难怪比较失败。


由于您想比较是否相等,第一步是查看两个字符串是否具有相同的长度。如果没有,您已经知道答案了。
如果它们的长度相同,则将其用作计数器CX。

; String1 pointer in DS:SI, length in CX
; String2 pointer in ES:DI, length in DX

cmp  cx, dx
jne  NotEqual
repe cmpsb
jne  NotEqual
Equal:       ; .showinfo:
...          ; The output string if both string are the same.
; Don't fall through here!!!
NotEqual:
...

【讨论】:

  • repe 的结束状态也处理不正确。 (通过cmp cx,0 而不是jcxz 或者更确切地说测试jne 状态来销毁它)。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-03-02
  • 1970-01-01
  • 2016-06-30
  • 2016-06-25
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多