Skip to main content
4 of 4
Tinkering with format
SirPython
  • 13.3k
  • 3
  • 38
  • 93

Countdown program in x86 NASM

I am fairly new to Assembly language programming and, for practice, I gave myself a problem: count down from 10 and right after 1, say "Blast off!".

section .text
    global _start
_start:
    mov eax, '10' ; asci 10
    mov [num], eax ; num now equals ascii 10

    mov edx, 2
    mov ecx, num
    mov ebx, 1
    mov eax, 4
    int 80h ; prints out '10' in the console

    mov eax, 9 ; numerical 9
    call subtract
subtract:
    call log ; logs the current number

    sub eax, 1 ; subract 1

    cmp eax, 0
    jne subtract ; if it doesn't equal 0, jump to subtract
    je blast_off ; if it does equal 0, jump to blast off
log:
    call to_ascii ; converts eax's value to ascii
    mov [num], eax ; num = eax
    mov edx, 1
    mov ecx, num
    mov ebx, 1
    mov eax, 4
    int 80h ; output the current number
    call to_number ; converts eax back to numerical
    ret
to_number:
    mov eax, [num] ; is this necessary? Moves num back into eax
    sub eax, '0' ; converts to numerical
    ret
to_ascii:
    add eax, '0' ; converts to ascii
    ret
blast_off:
    mov edx, len
    mov ecx, msg
    mov ebx, 1
    mov eax, 4
    int 80h ; outputs "Blast off!"

    mov eax, 1
    int 80h ; exits program
section .data
    msg db "Blast off!", 0xA ; message
    len equ $-msg ; length of message
section .bss
    num resb 1 ; this is for outputting the current number

Output:

1098654321Blast off!

Assembled: nasm -f elf blast_off.s

Linked: ld -m elf_i386 -s -o blast_off blast_off.o

My main concerns are:

  1. My code seems functional - is this bad, or does it not really matter, being assembly language?
  2. Is there repetition? This was a very difficult challenge for me, and at times I lost my head - sometime during those times I might have typed something completely "off topic" in regards to the subject of the code
  3. Aside from the first concern, does the organization need re-organizing? As in, should I reorder the different sections(.test, .data, .bss)? Or, does it not make a difference?
SirPython
  • 13.3k
  • 3
  • 38
  • 93