【问题标题】:understand cmpb and loops in assembly language了解汇编语言中的 cmpb 和循环
【发布时间】:2016-08-28 20:28:14
【问题描述】:

我有一个具有以下汇编代码的函数 string_length

0x08048e90 <+0>:     push   %ebp
0x08048e91 <+1>:     mov    %esp,%ebp
0x08048e93 <+3>:     mov    0x8(%ebp),%edx     // assign whatever I declared into edx
0x08048e96 <+6>:     mov    $0x0,%eax          // assign eax = 0
0x08048e9b <+11>:    cmpb   $0x0,(%edx)        // compare edx to byte of 0 (null..?)
0x08048e9e <+14>:    je     0x8048ea9 <string_length+25>   // if equal, jump to +25
0x08048ea0 <+16>:    add    $0x1,%eax          // else, add 1 to eax
0x08048ea3 <+19>:    cmpb   $0x0,(%edx,%eax,1) // compare byte 1*eax+edx with 0, 
0x08048ea7 <+23>:    jne    0x8048ea0 <string_length+16>   // if not equal, back to +16
0x08048ea9 <+25>:    pop    %ebp               // pop ebp
0x08048eaa <+26>:    ret

由于函数名是string_length,我假设它会返回字符串中有多少个字符。

我很困惑的是

cmpb   $0x0,(%edx)

这是比较指向 edx 的任何内容与 0 的字节,而 ASCII 中的 0 为空..?

cmpb   $0x0,(%edx,%eax,1)

以字节为单位比较 1*eax+edx。如果edx是一个字符串,是不是意味着edx会先转换成它的ascii值再进行计算?

【问题讨论】:

    标签: assembly


    【解决方案1】:

    这个:

    cmpb   $0x0,(%edx)
    

    获取 EDX 指向的字节(即包含地址)并将其与零进行比较。这个:

    cmpb   $0x0,(%edx,%eax,1)
    

    获取 EDX+EAX 指向的字节并将其与零进行比较。 EDX 用作字符串基指针,EAX 是索引。 Scale 为 1,因为我们使用的是字节。这样想整个循环:for(eax=0; edx[eax] != 0; eax++)

    【讨论】:

      【解决方案2】:

      等效的 C 代码如下所示:

      int string_length(const char *edx)
      {
          int eax = 0;
          while (edx[eax] != NULL) eax++;
          return eax;
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-02-13
        • 2013-02-01
        • 1970-01-01
        • 2012-01-08
        • 1970-01-01
        • 2021-12-02
        • 1970-01-01
        相关资源
        最近更新 更多