在汇编中填充数字数组

时间:2014-07-02 14:56:36

标签: assembly nasm

我编写了以下代码,以便使用数字字符串9876..1234填充数组:

segment     .data
  counter   dd 9877
  count     dd 8642
  array     times 9876 dd '0000' 

segment     .bss
  buffer    resb  4 

segment     .text
  global    _start

  _start: 

  mov ecx, [count]

  mov edx, array
  mov dword [pointer], array 

  l1:
    push ecx
    push edx

    dec dword [counter]                      ; decrease the counter
    lea esi, [buffer]
    mov eax, [counter]
    call int_to_string

    mov ecx, eax ; "begin print" position
    xor edx, edx
getlen:
    cmp byte [ecx + edx], 10
    jz gotlen
    inc edx
    jmp getlen
gotlen:
    inc edx

    push eax                             ; printing the string converted
    mov eax, 4
    mov ebx, 1
    int 0x80
    pop eax                              ; printing the string converted


    pop edx                              ; copying the string to array
    mov [edx], eax
    add edx, 4

    pop ecx
  loop l1


  mov ecx, [count]                  ;printing the array
  mov eax, array
  l2:
    push ecx

    mov [pointer], eax
    push eax

    mov eax, 4
    mov ebx, 1
    mov ecx, pointer
    mov edx, 4
    int 0x80

    pop eax
    add eax, 4

    pop ecx
  loop l2

  mov   eax, 1
  mov   ebx, 0
  int   0x80

int_to_string:
  add   esi, 9 ; counter + 9 ?
  mov   byte [esi], 10
  mov   ebx, 10         

.next_digit:
  xor   edx, edx        
  div   ebx             
  add   dl, '0'          
  dec   esi             
  mov   [esi],dl
  test  eax, eax            
  jnz   .next_digit
  mov   eax, esi
  ret

打印输出会在屏幕上打印随机字符。什么会导致我的代码?

1 个答案:

答案 0 :(得分:1)

三个中心错误:

1)“缓冲区”太小&指针丢失。

更改

segment     .bss
  buffer    resb  4

segment     .bss
  buffer    resb  10
  pointer   resd 1


2)“复制”是错误的。

更改

pop eax                              ; printing the string converted


pop edx                              ; copying the string to array
mov [edx], eax
add edx, 4

pop eax                              ; printing the string converted

mov eax, [eax]
pop edx                              ; copying the string to array
mov [edx], eax
add edx, 4


3)“打印”是错误的。

更改

mov eax, 4
mov ebx, 1
mov ecx, pointer
mov edx, 4
int 0x80

mov eax, 4
mov ebx, 1
mov ecx, [pointer]
mov edx, 4
int 0x80