Pejman Moghadam / Assembly

Linux Assembly - Convert hexadecimal number to decimal

Public domain


; Convert a hexadecimal number to decimal
; Filename : convert.asm
; Compile  : nasm -g -f elf convert.asm -o convert.o -l convert.lst
; Link     : ld -dynamic-linker /lib/ld-linux.so.2 -lc convert.o  -o convert
; Debug    : gdb convert -x GDBcmds
; GDBcmds  : 
;   display/10i $eip
;   display/x $eax
;   display/x $ebx
;   display/x $ecx
;   display/x $edx
;   display/x $edi
;   display/x $esi
;   display/x $ebp
;   display/32xw $esp
;   break main
;   break _start

SECTION .data
$hex:   equ     0x1BD0          ; Max: 0xFFFFFFFF


SECTION .bss
$dec:   resb    11              ; Max: 4,294,967,295 + '\n'


SECTION .text
global _start
_start:
        nop
        mov     esi, $dec+11    ; pointer to the end of decimal number
        mov     byte[esi], 0xa  ; add '\n'
        mov     eax, $hex
        mov     ebx, 0xa        ; hex number will divide to 10
        mov     ecx, 1          ; decimal number length + '\n'

$NEXT_DIGIT:
        inc     ecx             ; calculate output length
        xor     edx, edx        ; remainder storage should be 0 before divide
        div     ebx             ; divide hex number to 10
        add     edx, 0x30       ; calculate ascii code of remainder
        dec     esi             ; calculate decimal digit place
        mov     [esi], dl       ; put decimal digit into string
        cmp     eax, 0          ; is there hex digits any more?
        jnz     $NEXT_DIGIT

        ; show decimal number
        mov     edx, ecx        ; third argument:  string length
        mov     ecx, esi        ; second argument: pointer to string
        mov     ebx, 1          ; first argument:  file handle (stdout)
        mov     eax, 4          ; system call number (sys_write)
        int     0x80            ; call kernel

        ; exit
        mov     ebx, 0          ; return value
        mov     eax, 1          ; system call number (sys_exit)
        int     0x80            ; call kernel

BY: Pejman Moghadam
TAG: asm, hex
DATE: 2013-01-09 08:08:42


Pejman Moghadam / Assembly [ TXT ]