I'm trying to work up to being able to print the hailstone sequence in assembly. To do that though, I first needed to learn how to actually print a number out using the
write system call.
After a few design iterations, I ended up using division to get each digit one at a time by using the remainder. Each remainder gets pushed onto the stack, then the address of the stack is given to the system call to print out.
What I'd like advice on:
In a couple places, I have math split out over multiple lines, like:
sub edx, esp ; Calculate how many were pushed dec edx
It doesn't seem like it's possible to combine that into something like
sub edx, esp - 0, but if there is a neater way, I'd like to know.
This is my first time using
div. Is there anything wrong with how I'm using it? Also, is there a sane way of not using
divaltogether? Apparently it's stupid slow and should be avoided if possible.
Anything else notable. I'm a super-beginner, and this code is quite verbose.
n to represent the number that I want to print out. In theory though, that number could come from anywhere. It's just a placeholder for the exercise.
global _start section .data n: dd 123456 section .text _start: mov ebp, esp ; So we can tell how many were pushed mov ecx, [n] .loop: mov edx, 0 ; Zeroing out edx for div mov eax, ecx ; Num to be divided mov ebx, 10 ; Divide by 10 div ebx mov ecx, eax ; Quotient add edx, '0' push edx ; Remainder cmp ecx, 0 jne .loop mov eax, 4 ; Write system call mov ebx, 1 ; STDOUT mov ecx, esp ; The string on the stack mov edx, ebp sub edx, esp ; Calculate how many were pushed dec edx int 0x80 mov eax, 1 mov ebx, 0 int 0x80
Assembled and linked using:
nasm numprint2.asm -g -f elf32 -Wall -o numprint2.o ld numprint2.o -m elf_i386 -o numprint2