使用x86 32位Linux sys_write (NASM)打印整数



我是这个论坛的新手。我有一点高级语言的经验(真的很少)。近一个月前,我想看看汇编是如何工作的是个好主意,所以在linux上选择了nasm (IA-32)之后,我开始从教程中学习。

现在,在结束它之后,我试着写一个简单的程序,你可以让计算机打印一个100个数字的列表(1 2 4 8 16…),但我甚至不能正确地完成它。我得到这样的输出:

1PPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPP(continues)...

程序如下:

section .text
    global main
main:
    mov word [num], '1'
    mov ecx, 100
doubl:
    push ecx ; to push the loop counter
    mov eax, 4
    mov ebx, 1
    mov ecx, num
    mov edx, 1
    int 0x80
    sub ecx, 30h
    add ecx, ecx   ; shl ecx, 1
    add ecx, 30h
    mov [num], ecx   ; deleting this line I get  11111111111111111...
    pop ecx  ; to pop the loop counter
    loop doubl
exit:
    mov eax, 1
    int 0x80    
section .bss
num resw 2

看起来错误是在数字加倍的部分或在变量'num'中存储它的部分,但我不明白为什么会发生这种情况以及如何解决它。

顺便问一下,谁能告诉我什么时候用方括号呢?有什么规则吗?教程将其称为"有效地址",看起来当我想移动(或处理)变量的内容时,我必须使用括号,而不是对变量的地址进行操作。但我对此很困惑。我看到它用在:

mov ebx, count
inc word [ebx]
mov esi, value
dec byte [esi]

但不是很明显,一个人想要增加寄存器的内容(因为它没有地址(或者它有吗?)?

你的数字很快就会比个位数大。你应该做的是在num中有一个整数而不是一个字符,然后将该整数转换成可以用sys_write打印的字符串。

这里有一种转换方法:重复除以10,先取最小的数字作为余数:

; Input:
; eax = integer value to convert
; esi = pointer to buffer to store the string in (must have room for at least 10 bytes)
; Output:
; eax = pointer to the first character of the generated string
; ecx = length of the generated string
int_to_string:
  add esi,9
  mov byte [esi],0    ; String terminator
  mov ebx,10
.next_digit:
  xor edx,edx         ; Clear edx prior to dividing edx:eax by ebx
  div ebx             ; eax /= 10
  add dl,'0'          ; Convert the remainder to ASCII 
  dec esi             ; store characters in reverse order
  mov [esi],dl
  test eax,eax            
  jnz .next_digit     ; Repeat until eax==0
  ; return a pointer to the first digit (not necessarily the start of the provided buffer)
  mov eax,esi
  ret

可以这样使用:

    mov    dword [num],1
    ...
    mov    eax,[num]       ; function args using our own private calling convention
    mov    esi,buffer
    call   int_to_string
; eax now holds the address that you pass to sys_write
    ...
section .bss
    num    resd 1
    buffer resb 10

可以简化为shl dword [num],1。或者更好的是,当它仍然在add eax,eax的寄存器中时,在某个时刻将其加倍。

最新更新