I’m learning some basic arithmetic using NASM on Linux. I need to divide two numbers using variables NUMBER1 and NUMBER2. My code works if I type in actual value instead of variables. For example if I type in ‘6’ instead of NUMBER2 and ‘2’ instead of NUMBER1, the program does division and gives me answer of 3. Running code with variables gives FLOATING EXCEPTION (CORE DUMPED). could please explain how correctly use variables in this code? While debugging, I see that the problem is in DIV line. Thank you !
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
Advertisement
Answer
Because given example is supposed to process ASCII codes for numbers, not numbers themselves. If you enter 6
instead of '6'
, 6 - '0'
evaluates to 65494
(not 6
). If you try to divide further by 2
, processor is unable to store quotient in lower half of ax
register.
If you do not intend to output result to console and only try to learn how division with one byte integer works using assembler, pick your favourite debugger, place breakpoint after division operation and enjoy your result.
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