0

I'm trying to create a print_hex function that converts a hex value in register bx into a character array and I am struggling to realize why is nasm is telling me that I have an invalid effective address. My print_hex function looks like this:

print_hex:
pusha

; shift counter
mov ax, 12

ph_loop:
    ; if bx is 0 just print the predefined "0000" on hex_buff
    test bx, bx
    jz ph_loop_end

    mov cx, bx
    ; mask cx to have only the first character
    and cx, 0x000F
    ; use cx as the offset in the table and bring the character into cx (this is where the compile error happens)
    mov cx, [hex_table + cx]
    ; copy into a buffer the character that i just brought (using cl because for some reason if I use cl it copies 2 characters from the table)
    mov [hex_buff], cl

    shr bx, ax
    ; decrement counter by 4
    sub ax, 4
    jmp ph_loop
ph_loop_end:

mov bx, hex_buff
call print_string

popa
ret

Some more info this is being run as a bootsector program. I have read a couple of articles about using lea but I am not sure if I could use it here.

Peter Cordes
  • 328,167
  • 45
  • 605
  • 847
G.P
  • 1
  • 1
    `[hex_table + cx]` would work with a valid 16-bit-addressing-mode register like BX. e.g. just swap how you're using BX and CX and your code should work. Except you also need a pointer into `hex_buff` instead of overwriting the first byte repeatedly :P Consider stosb or `mov [di], bl` / `inc di`. The 2nd half of [Converting bin to hex in assembly](https://stackoverflow.com/q/40818086) shows a working example of that. – Peter Cordes Apr 08 '20 at 17:05
  • @PeterCordes Thank you for the fast answer I'll read upon that article you linked. And thank you for catching that bug! – G.P Apr 08 '20 at 17:30
  • Cheers, no worries. Also related: [How to convert a binary integer number to a hex string?](https://stackoverflow.com/q/53823756) is a 32-bit Q&A with scalar and SIMD that can do a whole number in a few shuffle instructions. Oh and BTW, `shr bx, ax` isn't valid either. Shift counts have to be immediate (186 or later) or in `cl`. But you could use a constant shift by 4 and go backwards in the output buffer, starting with the last digit. And then you can use the FLAGS result of the shift as the loop condition, like `shr ax, 4` / `jnz ph_loop`. – Peter Cordes Apr 08 '20 at 17:53

0 Answers0