How to resolve the algorithm Loops/While step by step in the X86 Assembly programming language

Published on 12 May 2024 09:40 PM

How to resolve the algorithm Loops/While step by step in the X86 Assembly programming language

Table of Contents

Problem Statement

Start an integer value at   1024. Loop while it is greater than zero. Print the value (with a newline) and divide it by two each time through the loop.

Let's start with the solution:

Step by Step solution about How to resolve the algorithm Loops/While step by step in the X86 Assembly programming language

Source code in the x86 programming language

; NASM 64 bit X86-64 assembly on Linux

global main
extern printf

segment .data

printffmt db `%ld\n`,0

segment .text

main:	                     
    push rbp                    
    mov rbp,rsp 
    
; used rbx and r12 because printf preserves these values
    
    mov rbx,1024                 ; start with 1024
    mov r12,2                    ; load 2 as divisor

.toploop                         ; top of while loop    
    cmp rbx,0                    ; compare to 0
    jle .done                    ; exit 0 or less
    
    lea rdi,[printffmt]          ; print number in rsi
    mov rsi,rbx                  ; mov to rsi as argument
    call printf

; calculate n/2 and save
    xor rdx,rdx                  ; clear rdx for division
    mov rax,rbx                  ; mov number to rax for division
    idiv r12                     ; divide by 2
    mov rbx,rax                  ; save n/2

    jmp .toploop                 ; next loop

.done
    xor rax,rax                  ; return code 0
    leave                        ; fix stack
    ret                          ; return

  

You may also check:How to resolve the algorithm Here document step by step in the BASIC programming language
You may also check:How to resolve the algorithm 2048 step by step in the FutureBasic programming language
You may also check:How to resolve the algorithm Sierpinski triangle step by step in the BCPL programming language
You may also check:How to resolve the algorithm Averages/Root mean square step by step in the PureBasic programming language
You may also check:How to resolve the algorithm Leonardo numbers step by step in the C# programming language