首页 > 解决方案 > Nasm 中的打印数字批评

问题描述

我写的“方法”是Nasm 64bit 模式。我只是想要一些建议,因为我刚刚开始在 Nasm 中编码,所以我可以做得更好。例如,有没有一种方法可以使用更少的寄存器,或者我的命名约定很糟糕(它们可能是!),有没有更好的方法来打印负值等。

bits 64

section .text
global _start

_start:
;debugging
 mov rbp, rsp

 push -666 ;number I want to print
 call _printVal ;calling the print "method"

 ;exit
 mov rax, 1
 mov rbx, 0
 int 80h


 _printVal:
 ;prolog
 push rbp
 mov rbp, rsp
 ;save registers
 push rbx
 push rdi
 push rsi

 ;actual code
 mov rax, [rbp + 16];get value user wants to print
 mov rbx, 10 ;we will be dividing by the to get the last digit
 xor rcx, rcx ; clear the rcx register as this will be out counter

 cqo; extend the flag
 cmp rdx, -1 ;check to see if negative
 jne _divisionLoop;if not negative jump
 ;print negative sign
 push 45;negative sign value
 mov rax, 1; sys_write
 mov rdi, 1; stdout
 mov rsi, rsp ; address to what to print
 mov rdx, 1 ; how many bytes is it
 syscall
 pop rax ;pop negative sign value from stack
 mov rax, [rbp + 16]; get user value again
 converting negative value to positive
 dec rax
 not rax
 xor rcx, rcx; clear rcx because of syscall again
 
 _divisionLoop:
    xor rdx, rdx
    div rbx ;divides number by 10 to move over last digit into rdx reg
    push rdx ;pushes the remainder onto the stack
    inc rcx   ; count for how many digits added to stack
    cmp rax, 0
 jnz _divisionLoop ;jump if the division did not result in a zero

 mov rax, 1; sys_write
 mov rdi, 1; stdout
 mov rdx, 1; 1 byte long


  _printToScreenVal:
    mov rsi, rsp; pop value from stack (most significant digit)
    push rcx; (save rcx)

    mov rcx, 48
    add [rsi], rcx; add 48 to make it into ASCII value

    syscall
    pop rcx; get rcx register back
    pop rbx; pop most siginificant digit
    dec rcx; decrement how many more digits i have to print
  jnz _printToScreenVal

  ;restore register
  pop rsi
  pop rdi
  pop rbx
  ;epilog
  pop rbp
  ret

标签: numbersx86-64nasm

解决方案


推荐阅读