NASM部门使用变量而不是实际值

时间:2018-01-30 21:35:56

标签: linux math assembly nasm division

我在Linux上使用NASM学习一些基本的算法。我需要使用变量NUMBER1和NUMBER2来划分两个数字。如果我键入实际值而不是变量,我的代码就可以工作。例如,如果我键入'6'而不是NUMBER2和'2'而不是NUMBER1,程序会进行除法并给出3的答案。 使用变量运行代码会产生FLOATING EXCEPTION(CORE DUMPED)。请解释一下如何正确使用此代码中的变量? 在调试时,我发现问题出在DIV行中。谢谢!

 section .text

global main ;must be declared for using gcc

main: ;tell linker entry point
mov ax,[NUMBER2]
sub ax, '0'
mov bl, [NUMBER1]
div bl
add ax, '0'
mov [res], ax
mov ecx,msg
mov edx, len
mov ebx,1 ;file descriptor (stdout)
mov eax,4 ;system call number (sys_write)
int 0x80 ;call kernel
nwln
mov ecx,res
mov edx, 1
 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
NUMBER1: dw 2
NUMBER2: dw 6
msg db "The result is:", 0xA,0xD
len equ $- msg

segment .bss
res resb 1

1 个答案:

答案 0 :(得分:1)

因为给定的例子应该处理数字的ASCII码,而不是数字本身。如果您输入6而不是'6',则6 - '0'会评估为65494(而不是6)。如果您尝试进一步除以2,则处理器无法在ax寄存器的下半部分存储商。

如果您不打算将结果输出到控制台,并且只尝试使用汇编程序了解如何使用汇编程序对一个字节整数进行除法,请选择您喜欢的调试器,在除法运算后放置断点并享受结果。

section .text

global main ;must be declared for using gcc

main: ;tell linker entry point
mov ax,[NUMBER2]
mov bl, [NUMBER1]
div bl
nop ; quotient at al, remainder at ah
; remove nop instruction if your code is larger than few lines
; place output code here

section .data
NUMBER2: dw 6 ; dw means two bytes
NUMBER1: db 2 ; db means one byte

segment .bss
res resb 1