打印数组所有元素的汇编代码

标签 assembly x86

我一直在尝试打印数组的元素。我有这段代码,它对数组的所有元素求和并打印结果,我尝试以多种方式进行编辑,但没有成功。

这是我在互联网上找到的代码:

    section .text
    global _start   ;must be declared for linker (ld)
_start: 

      mov  eax,3      ;number bytes to be summed 
      mov  ebx,0      ;EBX will store the sum
      mov  ecx, x     ;ECX will point to the current element to be summed
top:  add  ebx, [ecx]
      add  ecx,1      ;move pointer to next element
      dec  eax        ;decrement counter
      jnz  top        ;if counter not 0, then loop again
done: 
      add   ebx, '0'
      mov  [sum], ebx ;done, store result in "sum"
display:
      mov  edx,1      ;message length
      mov  ecx, sum   ;message to write
      mov  ebx, 1     ;file descriptor (stdout)
      mov  eax, 4     ;system call number (sys_write)
      int  0x80       ;call kernel
      mov  eax, 1     ;system call number (sys_exit)
      int  0x80       ;call kernel

section .data
global x
x:    
      db  2
      db  4
      db  3
sum: 
      db  0

这就是我编辑它的方式,但没有运气(我尝试了很多其他的东西)。这会打印第一个元素“2”并给出段错误错误。

编辑:这是工作代码,谢谢大家,谢谢ElderBug! :)

_start: 

      mov  esi,3      ;number bytes to be traversed 
      mov  edi, x     ;EDI will point to the current element to be summed
      mov  eax, 0     ;eax will hold the text to print

top:  

      mov eax, [edi] ;store current element
      add  edi,1      ;move pointer to next element

      add  eax, '0' ;do the conversion
      mov [toprint], eax


      mov  ecx, toprint ;message to write
      mov  edx,1      ;message length
      mov  ebx, 1     ;file descriptor (stdout)
      mov  eax, 4     ;system call number (sys_write)
      int  0x80       ;call kernel



      dec  esi        ;decrement counter
      jnz  top        ;if counter not 0, then loop again

      mov  eax, 1     ;system call number (sys_exit)
      int  0x80       ;call kernel



   section  .data
    global x
    x:    
          db  2
          db  4
          db  3

   toprint:

         dw 'x'

我知道“int 0x80”样式4意味着写入,第一个参数存储在ebx中,第二个参数存储在ecx中,第三个参数存储在edx中。但无法弄清楚这一点。

最佳答案

您所说的对您有效的解决方案仍然存在严重问题!

  • 因为toprint被定义为单词,所以您不应该使用指令mov [toprint]在其中写入dword值,eax
  • 由于数组元素被定义为 byte,因此您不应使用指令 mov eax, [edi] ;store current element 将它们读取为 dword.
  • sys_exit 使用 EBX 作为第二个参数。

它应该是这样的

top:  
 mov al, [edi]     ;store current element
 add edi, 1        ;move pointer to next element
 add al, '0'       ;do the conversion
 mov [toprint], al

请研究@David C. Rankin 给出的评论。这对您的目的非常有用。

关于打印数组所有元素的汇编代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30057396/

相关文章:

assembly - 使用 Winasm 创建 .inc 、 .lib 和 dll

c - 关于栈指针的疑问

gcc - 什么 '__asm__(".previous");'意思?

assembly - 气体 : too many memory reference

c - 为 __m256i 分配内存

x86 - 带增量的 AVX 加载指令

assembly - 我可以在哪些 Intel CPU 上使用 umonitor 和 umwait 指令?

assembly - 如何在汇编中将正数转换为负数

c - 堆栈分配、填充和对齐

macos - 这个汇编函数序言/尾声代码对 rbp/rsp/leave 有什么作用?