2013-10-11 51 views
3

好的,所以我对组装很新,事实上,我对装配很陌生。我写了一段代码,它只是简单地将用户的数字输入,乘以10,并通过程序退出状态(通过在终端中输入echo $?)向用户表达结果。 问题是,它没有给出正确的数字,4x10显示为144.那么我认为输入可能是一个字符,而不是一个整数。我的问题在于,如何将字符输入转换为整数,以便在算术计算中使用它?NASM Assembly将输入转换为整数?

这将是伟大的,如果有人可以回答记住,我是一个初学者:) 另外,我怎么能说所有的整数回到一个字符?

section .data 

section .bss 
input resb 4 

section .text 

global _start 
_start: 

mov eax, 3 
mov ebx, 0 
mov ecx, input 
mov edx, 4 
int 0x80 

mov ebx, 10 
imul ebx, ecx 

mov eax, 1 
int 0x80 
+0

我设法比较用户输入和数字: mov ecx,dword [input] 这是否实际上将ecx中的值更改为一个整数? 以及如何将其更改回字符串? – user2862492

回答

7

这里有一个字符串转换为整数,一对夫妇的功能,反之亦然:

; Input: 
; ESI = pointer to the string to convert 
; ECX = number of digits in the string (must be > 0) 
; Output: 
; EAX = integer value 
string_to_int: 
    xor ebx,ebx ; clear ebx 
.next_digit: 
    movzx eax,byte[esi] 
    inc esi 
    sub al,'0' ; convert from ASCII to number 
    imul ebx,10 
    add ebx,eax ; ebx = ebx*10 + eax 
    loop .next_digit ; while (--ecx) 
    mov eax,ebx 
    ret 


; Input: 
; EAX = integer value to convert 
; ESI = pointer to buffer to store the string in (must have room for at least 10 bytes) 
; Output: 
; EAX = pointer to the first character of the generated string 
int_to_string: 
    add esi,9 
    mov byte [esi],STRING_TERMINATOR 

    mov ebx,10   
.next_digit: 
    xor edx,edx   ; Clear edx prior to dividing edx:eax by ebx 
    div ebx    ; eax /= 10 
    add dl,'0'   ; Convert the remainder to ASCII 
    dec esi    ; store characters in reverse order 
    mov [esi],dl 
    test eax,eax    
    jnz .next_digit  ; Repeat until eax==0 
    mov eax,esi 
    ret 

这是你将怎样使用它们:

STRING_TERMINATOR equ 0 

lea esi,[thestring] 
mov ecx,4 
call string_to_int 
; EAX now contains 1234 

; Convert it back to a string 
lea esi,[buffer] 
call int_to_string 
; You now have a string pointer in EAX, which 
; you can use with the sys_write system call 

thestring: db "1234",0 
buffer: resb 10 

请注意,我不在这些例程中不做太多错误检查(例如检查是否有'0' - '9'范围之外的字符)。例程也不处理带符号的数字。所以如果你需要这些东西,你必须自己添加它们。