2013-03-14 46 views
0

我试图在NASM中编写代码来获取给定字符串的长度。但是会给出一些垃圾值作为长度。该代码是以下之一:使用NASM的字符串的长度

section .data 
     a db "nitin",10,0 
     msg db "length = %d",10,0 
    section .text 
     global main 
     extern printf 
    main: 
     nop 
     xor eax,eax 
     mov eax, a 
     xor edx,edx 
    length: 
     mov dl, byte[eax] 
     cmp dl,0 
     je print 
     inc eax 
     jmp length 

    print: 
     pusha 
     push eax 
     push msg 
     call printf 
     add esp,8 
     popa 
    done: 
     nop 

结果显示: 长度= 132445678

能否请你帮我理清我的错误?

谢谢

回答

6

EAX程式码中有如下的字节,而不是字符串中的索引的地址。所以,而不是长度,你打印出终止空字符的地址。

要么重新形成EAX从零开始读取地址[a + eax]处的字节,要么在打印出长度之前从EAX中减去a的地址。要么会工作。

编辑:对于第一种方法,主循环是这样的:

main: 
    nop 
    xor eax,eax ; removed the mov eax,a line - eax stays zero 
    xor edx,edx 
length: 
    mov dl, byte[a+eax]   ; eax is the index in the string 
    cmp dl,0 
    ;The rest stays the same 

对于第二种方法中,循环保持不变,但印刷部分得到一个额外的sub

print: 
    sub eax, offset b ; convert from address to index 
    pusha 
    push eax 
    push msg 
    ; The rest is the same 

然而,这将是最短途径:

main: 
    nop 
    mov edi, a ; the string we're scanning 
    xor al, al ; That's what we're scanning the string for - a null valued byte 
    mov ecx, 0ffffffffh ; we bet on string being null terminated - no hard limit on string scanning 
    repne scasb ; Once this finishes, ECX is (0xffffffff - length - 1) (because the terminating null is counted too) 
    mov eax, 0fffffffeh 
    sub eax, ecx ; Now eax is (0xffffffff - 1 - ecx), which is string length 
print: 
    ; Same as before 

中查找scas命令以及如何将它与repxx前缀一起使用。这几乎就像是在Intel CPU指令集中实现了一部分C RTL(strlen,strcpy等)。

在旁注中,片段有两个完全无关的行 - xor eax, eaxxor edx, edx在函数的开头。无论如何,两个寄存器都将被覆盖在下一行。

+0

谢谢你的回复。我已经使用计数器寄存器ecx解决了它。然而,我想知道如何使用eax来解决这个问题,对不起,导师,我仍然没有得到如何使用eax解决它。 – sabu 2013-03-14 15:12:40

+0

其实,最快的方法就是al rep = 0的'rep scasb'。让你完全避免循环。 – 2013-03-14 18:27:27

+0

梦幻般的anaysis.A学生只需要这个.Fantastic,我的导师 – sabu 2013-03-15 07:47:52