linux - 如何在 Gasm (Gnu Assembler) 中比较符号和字符串?

标签 linux assembly 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 语法。但是,您应该了解您的问题是什么以及如何解决它。

关于linux - 如何在 Gasm (Gnu Assembler) 中比较符号和字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16750689/

相关文章:

linux - 汇编中的泰勒级数指数函数

colors - 具有深色背景的 gnu 源突出显示的配色方案

linux - 在 Docker 内部进行基准测试时消除 UnionFS 对结果的影响

linux - 可执行的 while 循环 : no such file or directory

linux - 如何在Linux中重命名所有包含破折号的子目录中的所有.jpg文件?

c++ - 为什么 `PSHUFD` 指令没有浮点内在函数?

PHP Curl 错误 35 - 同行报告不兼容或不受支持的协议(protocol)版本

c - LDMIA 指令导致损坏的寄存器数据

c++ - 重定位值不适合 24 位

linux - ELF文件格式中的section和segment有什么区别