【问题标题】:how to count the number of digits assembly code?如何计算汇编代码的位数?
【发布时间】:2009-01-16 11:02:14
【问题描述】:

假设我有一个用汇编语言编写的程序,它接受用户输入的句子(数字和字母的组合),下一行将显示句子中小写字母的数量。同时显示句子中的位数。

我的问题是:我怎样才能使计数指令来计算数字和字母?

【问题讨论】:

    标签: assembly


    【解决方案1】:

    我假设您的意思是 x86 程序集,并且字符串以 null 结尾。

    mov eax, STRING_VARIABLE
    xor ebx, ebx
    xor ecx, ecx
    .loop:
      mov dl, [eax]
      cmp dl, 0
      jz .end
    
      cmp dl, '0'
      jb .notdigit
      cmp dl, '9'
      ja .notdigit
      inc ecx
      jmp .notlowercase
      .notdigit:
      cmp dl, 'a'
      jb .notlowercase
      cmp dl, 'z'
      ja .notlowercase
      inc ecx
      .notlowercase:
    
      inc eax
      jmp .loop
    .end:
    ; ebx contains the lowercase letter count
    ; ecx contains the digit count
    

    【讨论】:

      【解决方案2】:

      如果它是一个Pascal字符串,字符串长度为第一个字节,你将修改如下;

      mov eax, STRING_VARIABLE
      xor ebx, ebx  ; A tiny bit quicker and shorter than mov ebx,0
      xor ecx, ecx
      mov dh,[eax]  ; dh is loop counter based on string length
      inc eax       ; move onto the string data
      .loop:
        cmp dh,0
        jz .end
        .
        .
        .
      .notlowercase:
        dec dh
        jmp .loop
      .end:
      

      【讨论】:

        【解决方案3】:

        我认为 Mehrdad 对要完成的工作有大致的了解;

        不过,只是一些观察——

        在“inc ecx”之后跳转到 .notlowercase 会节省几个周期,可能是疏忽 --

        我认为最后一个inc ecx应该是inc ebx

        对上/下测试略有改动,因为这是只有字母/数字字符,在.notdigit标签之后,小写测试可以替换为

        .notdigit:
            and   dl, 0x20
            jz   .notlowercase
            inc   ebx
        .notlowercase:
        

        只是我的 2 美分 -- :)

        【讨论】:

          【解决方案4】:

          这也会为 Unicode 字符串提供不正确的结果。给定 UTF-16,您需要将 eax 增加 2。如果您需要计算具有高字节集的字符,您也需要考虑到这一点。

          【讨论】:

            猜你喜欢
            • 2020-06-09
            • 1970-01-01
            • 1970-01-01
            • 2016-02-12
            • 1970-01-01
            • 1970-01-01
            • 2017-10-20
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多