Printing hex from dx with nasm

By : fr33g
Source: Stackoverflow.com
Question!

I actually want to print the content of the dx register with nasm. Thereby the content is a 16 bit hex digit such as 0x12AB.

Therefore I've first implemented a function which is able to print a string:

print_string:
    pusha
    mov ah, 0xe

print_character:
    mov al, [bx]
    inc bx
    or al, al
    jz print_done
    int 0x10
    jmp print_character

print_done:
    popa
    ret

You can use this function in this way:

mov bx, MSG
call print_string

MSG:
    db 'Test',0

Now i want to have a function, which converts the hex to a string, so that print_string is capable to print it. I was thinking about something like that:

print_hex:
    pusha
    mov bx, HEX_OUT
    ; HEX_OUT is a kind of template string
    ; now i want to get the hex of dx into this template in order to be able to print it
    ; However I'm not sure how to manage this
    call print_string
    popa
    ret

HEX_OUT:
    db '0x0000', 0

Unfortunately I'm not sure how I get the hex from dx into bx, respectively the HEX_OUT. Can someone help me or does someone have an idea?

I want to use it at the end like this:

mov dx, 0x12AA
call print_hex

Thanks you already in advance!

UPDATE:

As mentioned I could achieve the separating and printing like this:

print_hex:
    pusha
    mov bx, PREFIX
    call print_string

next_character:
    mov bx, dx
    and bx, 0xf000
    shr bx, 4
    add bh, 0x30
    cmp bh, 0x39
    jg add_7

print_character_hex:
   mov al, bh
   mov ah, 0x0e
   int 0x10
   shl dx, 4
   or dx, dx
   jnz next_character
   popa
   ret

add_7
   add bh, 0x7
   jmp print_character_hex

PREFIX:
   db '0x', 0

I tried something like this to print it with my function and the buffer:

print_hex:
    ;Added this here    
    mov cx, HEX_OUT + 2

print_character_hex:
    mov [cx], bh

Though I can't assemble this due to "invalid effective address". What do I need to do in order to accomplish this?

By : fr33g


Answers

All right, I was able to manage it. Thank you for your help! Here is the working code:

print_hex:
   pusha
   mov si, HEX_OUT   2

next_character:
  mov bx, dx
  and bx, 0xf000
  shr bx, 4
  add bh, 0x30
  cmp bh, 0x39
  jg add_7

add_character_hex:
  mov al, bh
  mov [si], bh
  inc si
  shl dx, 4
  or dx, dx
  jnz next_character
  mov bx, HEX_OUT
  call print_string
  popa
  ret

add_7:
  add bh, 0x7
  jmp add_character_hex

HEX_OUT:
  db '0x0000', 0
By : fr33g


This video can help you solving your question :)
By: admin