字符串到int坏输出Nasm

时间:2016-11-01 16:44:33

标签: assembly 64-bit nasm

我创建了将字符串更改为int的功能,但输出结果很糟糕。 例如,对于character db "1234" , 0,我输出11211231234而不是1234。也许有人知道我错在哪里。这是我的代码

%include "asm64_io.inc"

segment .data
character db "1234" , 0

segment .bss

segment .text

global asm_main
asm_main:
 enter 0,0 


mov rdx, character
call change_string_to_int
ret

change_string_to_int:
mov rcx, 0 ; licznik
mov rax, 0

_loop:
mov bl, [rdx + rcx]
test bl, bl
je _ex
sub bl, '0'
imul rax, 10
add rax, rbx
call print_int
inc rcx
jmp _loop



_ex:
mov rax, 0 
leave
ret

1 个答案:

答案 0 :(得分:0)

从字符串转换为数字的算法需要两件事:

  • 必须从右到左处理字符串字符(从最低位开始)。
  • 将每个字符乘以10的顺序幂(1,10,100,1000)。

这是你的代码有必要的更改,我添加变量number来存储最终结果并更改了一些寄存器,注释将帮助你理解:

%include "asm64_io.inc"

segment .data
character db "1234" , 0
number    dq 0            ;◄■■■ FINAL RESULT (THE NUMBER).

segment .bss

segment .text

global asm_main
asm_main:
 enter 0,0 

mov rbx, character        ;◄■■■ RBX BECAUSE RDX WILL BE LOST AFTER MUL. 
mov rcx, 3                ;◄■■■ LENGTH OF "CHARACTER" - 1 (LOOP COUNTER).
call change_string_to_int
;▼ DISPLAY RESULT.
  mov rax, number
  call print_int
ret

change_string_to_int:
mov rdi, 1                 ;◄■■■ POWER OF 10 (10^0=1). 

_loop:
;▼ GET CURRENT CHAR.                
  xor rdx, rdx             ;◄■■■ CLEAR RDX, SO RDX=DL.
  mov dl, [rbx + rcx]      ;◄■■■ GET CHARACTER FROM RIGHT TO LEFT.
  sub dl, '0'              ;◄■■■ CONVERT CHAR TO DIGIT.
;▼ MUTIPLY DIGIT BY CURRENT POWER OF 10.
  mov rax, rdi             ;◄■■■ RAX = CURRENT POWER OF 10.
  mul rdx                  ;◄■■■ DIGIT * POWER OF 10.
  add number, rax          ;◄■■■ ACCUMULATE RESULT (DISCARD RDX).
;▼ CALCULATE NEXT POWER OF 10.
  mov rax, rdi             ;◄■■■ RAX = CURRENT POWER OF 10.
  mov rdi, 10
  mul rdi                  ;◄■■■ RAX * 10.
  mov rdi, rax             ;◄■■■ RDI = NEXT POWER OF 10.
;▼ CHECK IF LOOP REPEATS.
  dec rcx
  cmp rcx, 0
  jge _loop                ;◄■■■ IF RCX>=0 REPEAT.
mov rax, 0 
leave
ret

我在call change_string_to_int后显示数字(我猜print_intrax的数字。)