NASM中的DIV始终返回1

时间:2018-11-12 12:31:49

标签: linux nasm

有我所有的代码:

SYS_EXIT  equ 1
SYS_READ  equ 3
SYS_WRITE equ 4
STDIN     equ 0
STDOUT    equ 1

section .data 

   msg1 db `\xF0\x9F\x98\x8E`, " Enter the A: "
   len1 equ $- msg1 

   msg2 db `\xF0\x9F\x98\x89`, " Than the B: "
   len2 equ $- msg2

   msg3 db `\xF0\x9F\x8D\xB0`, " A > B:   A / B - 1 = "
   len3 equ $- msg3

   msg4 db `\xF0\x9F\x8D\xAA`, " A = B: -25"
   len4 equ $- msg4

   msg5 db `\xF0\x9F\x8D\x95`, " A < B: (B^3 - 5) / A = "
   len5 equ $- msg5


section .bss

   a resb 32
   b resb 32
   x resb 32

section .text
   global _start    ;must be declared for using gcc

_start:             ;tell linker entry point
   mov eax, SYS_WRITE
   mov ebx, STDOUT
   mov ecx, msg1
   mov edx, len1
   int 0x80

   mov eax, SYS_READ
   mov ebx, STDIN
   mov ecx, a
   mov edx, 32
   int 0x80

   mov eax, SYS_WRITE
   mov ebx, STDOUT
   mov ecx, msg2
   mov edx, len2
   int 0x80

   mov eax, SYS_READ
   mov ebx, STDIN
   mov ecx, b
   mov edx, 32
   int 0x80

   ; Comparing
   mov eax, [a]
      sub eax, '0'
   mov ecx, [b]
      sub ecx, '0'

   cmp eax, ecx
   jg Ab          ;A grate than b
   je AB          ;A and B are equal
   jl aB          ;a smoller than B

   Ab:
      cdq
      idiv ecx
      dec eax

      add eax, '0'
      mov [x], eax

      mov eax, SYS_WRITE
      mov ebx, STDOUT
      mov ecx, msg3
      mov edx, len3
      int 0x80

      mov eax, SYS_WRITE
      mov ebx, STDOUT
      mov ecx, x
      mov edx, 32
      int 0x80
      jmp exit    ;go to exit

   AB:
      mov eax, SYS_WRITE        
      mov ebx, STDOUT         
      mov ecx, msg4
      mov edx, len4
      int 0x80
      jmp exit    ;go to exit

   aB:
      mov eax, ecx
      imul ecx
      imul ecx
         mov ebx, '5'
            sub ebx, '0'
      sub eax, ebx

      mov ecx, [a]
         sub ecx, '0'
      idiv ecx

      add eax, '0'
      mov [x], eax

      mov eax, SYS_WRITE
      mov ebx, STDOUT
      mov ecx, msg5
      mov edx, len5
      int 0x80

      mov eax, SYS_WRITE
      mov ebx, STDOUT
      mov ecx, x
      mov edx, 1
      int 0x80

exit:    

   mov eax, SYS_EXIT   
   xor ebx, ebx 
   int 0x80

在'a'和'b'中,我在0到9之间输入了不同的数字,但此操作始终返回1。我签出EDX,并注意到处理器仅从EAX中减去ECX一次。在EAX中,他写了1;在EDX中,他写了减去EAX和ECX的余数。

当我输入a = 9且b = 4时:除以= 1且EDX = 5后的EAX。如果我输入a = 6且b = 2时:EAX = 1,则EDX = 4

发生了什么事?

1 个答案:

答案 0 :(得分:0)

每个数字后面大概都有一个换行符(0xA)。因此,您最终将0xA09除以0xA04。您可以例如改为使用movzx eax, byte [a](和b相似)。