如何在Gasm (Gnu汇编器)中比较符号和字符串



我需要使用gasm计算字符串中的空格数量。所以,我写了一个简单的程序,但是比较不起作用。

.section .data
  str:
    .string " TEst   string wit h spaces   n"
.section .text
.globl _start
_start:
movl $0,%eax # %eax - amount of spaces
movl $0,%ecx # Starting our counter with zero
loop_start:
  cmpl $32,str(,%ecx,1)  # Comparison (this is never true)
  jne sp
  incl %eax # Programm never goes there
  incl %ecx
  jmp loop_start
sp:
  cmpl $0X0A,str(,%ecx,1) #Comparison for the end of string
  je loop_end #Leaving loop if it is the end of string
  incl %ecx
  jmp loop_start
loop_end:
  movl (%eax),%ecx  # Writing amount of spaces to %ecx
  movl $4,%eax
  movl $1,%ebx
  movl $2,%edx
  int $0x80
  movl $1,%eax
  movl $0,%ebx
  int $0x80

所以,这个字符串cmpl $32,str(,%ecx,1)的问题,我尝试将空间(ASCII中的32)与1字节的str(我使用%ecx作为位移计数器,并采用1字节)进行比较。不幸的是,我在互联网上没有找到任何关于Gasm中符号比较的例子。我曾尝试使用gcc生成的代码,但我无法理解和使用它。

这永远不会返回true,我想我知道为什么:

cmpl $32,str(,%ecx,1)

因为比较的是一个直接值和一个内存地址,汇编程序无法知道两个操作数的大小。所以,它可能假设每个参数是32位,但是你想比较两个8位的值。您需要以某种方式显式地声明您正在比较字节。我的解决方案是:

mov str(,%ecx,1), %dl  # move the byte at (str+offset) into 'dl'
cmp $32, %dl           # compare the byte 32 with the byte 'dl'.
# hooray, now we're comparing the two bytes!

可能有更好的方式显式比较字节,我可能犯了一个愚蠢的错误;我不太熟悉AT&T语法。但是,你应该知道你的问题是什么,以及如何解决它。

最新更新