Outputting integers in assembly on Linux

前端 未结 2 698
别跟我提以往
别跟我提以往 2020-12-10 16:13

This needs to be done in pure assembly (ie. no libraries or calls to C).

I understand the essence of the problem: one needs to divide the integer by 10, convert the

相关标签:
2条回答
  • 2020-12-10 17:00

    There are at least two more problems. beyond the corruption of ecx that @sarnold mentioned:

    1. div ecx divides the 64-bit value edx:eax by ecx, so you need to ensure that you set edx to 0 before the division.

    2. The second argument to the write system call (in ecx) should be a pointer to a buffer containing the character you want to print, not the character itself.

    One way to solve the second problem is to push the register containing the character you want to print on the stack, and then assign the stack pointer esp to ecx (the stack pointer points at the most recently pushed item, and x86 stores values little-endian, so the first byte is the low 8 bits). e.g.

    push edx         ; save value on stack
    mov  eax, 4      ; sys_write
    mov  ebx, 1      ; to STDOUT
    mov  ecx, esp    ; first byte on stack
    mov  edx, 1      ; length = one byte
    int  0x80
    pop  edx         ; remove what we pushed (or "add esp, 4" would do just as well here;
                     ;                        we don't need the actual value again)
    

    That should be enough to get some output...

    (But at that point, you might notice a "feature" of your algorithm, and want to re-think how you store the digits that are produced by the division!)

    0 讨论(0)
  • 2020-12-10 17:07

    You properly set ecx to 10 at the top of your routine, but overwrite ecx later:

    mov eax, 4              ; sys_write
    mov ebx, 1              ; to STDOUT
    mov ecx, edx ;;; oops -- lost the 10
    mov edx, 1
    int 0x80
    

    Try moving the loop up one line, so ecx is re-initialized to 10 each time through the loop.

    0 讨论(0)
提交回复
热议问题