This page looks best with JavaScript enabled

MercuryOS IF-ELSE in Assembly

 ·  πŸŽƒ kr0m

One of the most basic structures when starting to program are if statements. In this article, I will explain a very simple example in pseudocode and how to translate it to assembly language.

Before we begin, it is recommended that you read these previous articles:


In assembly language, we have different jump instructions:

  • je target ; jump if equal ( i.e. x == y)
  • jne target ; jump if not equal ( i.e. x != y)
  • jl target ; jump if less than ( i.e. x < y)
  • jle target ; jump if less than or equal ( i.e. x <= y)
  • jg target ; jump if greater than ( i.e. x > y)
  • jge target ; jump if greater than or equal ( i.e. x >= y)

The implementation of an if-else in ASM is quite simple, first let’s write the code in pseudocode and then see the equivalent in ASM:

bl = 4

print bl

if ax == 4:
 print '1'
else:
 print '2'
fi

print '3'

In assembly language it would be:

vi boot_sect_if.asm

mov bl, '4'
mov ah, 0x0e; tty mode

mov al, bl; print bl value
int 0x10

cmp bl, '4'; compare the value in bl to 4
je then_block; jump to then_block if they were equal
mov al, '2'; print 2
int 0x10
jmp the_end; important : jump over the ’then ’ block , so we don ’t also execute that code.

then_block:
    mov al, '1'; print 1
    int 0x10

the_end:
    mov al, '3'; print 3
    int 0x10

jmp $; jump to current address = infinite loop

; padding and magic number
times 510 - ($-$$) db 0
dw 0xaa55 

We generate the image:

nasm -f bin boot_sect_if.asm -o boot_sect_if.bin

We load it into qemu:

qemu-system-x86_64 boot_sect_if.bin

SeaBIOS (version rel-1.12.1-0-ga5cab58e9a3f-prebuilt.qemu.org)  
iPXE (http://ipxe.org) 00:03.0 C980 PCI2.10 PnP PMM+07F91410+07EF1410 C980  
  
Booting from Hard Disk...  
413

If we change the value of bl to 5:

vi boot_sect_if.asm

mov bl, '5'

We regenerate the image:

nasm -f bin boot_sect_if.asm -o boot_sect_if.bin

We load it into qemu:

qemu-system-x86_64 boot_sect_if.bin

SeaBIOS (version rel-1.12.1-0-ga5cab58e9a3f-prebuilt.qemu.org)  
iPXE (http://ipxe.org) 00:03.0 C980 PCI2.10 PnP PMM+07F91410+07EF1410 C980  
  
Booting from Hard Disk...  
523

We can see how the code execution is correct.

If you liked the article, you can treat me to a RedBull here