Tuesday, January 29, 2013

Read and print a 16 bit number in NASM

section .bss
  num: resw 1 ;For storing a number, to be read of printed....
  nod: resb 1 ;For storing the number of digits....
  temp: resb 2
section .text
  global _start

_start:
  call read_num
  call print_num

exit:
  mov eax, 1
  mov ebx, 0
  int 80h
 
;Function to read a number from console and to store that in num 
read_num:

  pusha
  mov word[num], 0
  
  loop_read:
    mov eax, 3
    mov ebx, 0
    mov ecx, temp
    mov edx, 1
    int 80h
    
    cmp byte[temp], 10
      je end_read
    
    mov ax, word[num]
    mov bx, 10
    mul bx
    mov bl, byte[temp]
    sub bl, 30h
    mov bh, 0
    add ax, bx
    mov word[num], ax
    jmp loop_read 
  end_read:
  popa
  
ret


;Function to print any number
print_num:
  pusha
  extract_no:
    cmp word[num], 0
    je print_no
    inc byte[nod]
    mov dx, 0
    mov ax, word[num]
    mov bx, 10
    div bx
    push dx
    mov word[num], ax
  jmp extract_no

  print_no:
    cmp byte[nod], 0
    je end_print
    dec byte[nod]
    pop dx
    mov byte[temp], dl
    add byte[temp], 30h


    mov eax, 4
    mov ebx, 1
    mov ecx, temp
    mov edx, 1
    int 80h
    
    jmp print_no
    
  end_print:   
  popa
ret 

No comments:

Post a Comment