assembly - 当我从命令行(ubuntu nasm 32bit)获取字符串时,如何将字符串转换为整数?
问题描述
%include "asm_io.inc"
segment .data
segment .bss
argument resb 32 ; argument[32]
segment .text
global main
main:
enter 0,0
mov ebx, 4
mov ecx, dword [ebp + 4 * ebx]
mov eax, dword [ecx + 4]
mov [argument], eax
mov al, byte [argument + 0]
sub al, 48
call print_int
end: leave
mov eax, 0
ret
我正在尝试将字符串从命令行转换为整数(例如,当我在命令行键入 $./Hello 30 时,'30' 必须是程序(过程)的整数参数)。在找到 [argument + 0] == '30', [argument + 1] = bin/bash 之后,我想我可以用 [argument + 0] 得到正确的数字。但结果就像-1075579555。
即使是一点点评论,也会很有帮助。谢谢你
解决方案
当您的程序启动时,堆栈的布局如下
0
Address of last environment string
...
Address of 2nd environment string
Address of 1st environment string
0
Address of last program argument
...
Address of 2nd program argument
Address of 1st program argument
Address of program path
ESP -> Number of arguments
对于您的任务,您需要获取第一个程序参数的地址。
您会在dword [esp + 8]
.
在执行之后enter 0,0
并且因为该指令推送了EBP
寄存器,你会在dword [esp + 12]
==找到它dword [ebp + 12]
。
enter 0,0 ; Same as PUSH EBP : MOV EBP, ESP
mov ebx, dword [ebp + 12] ; Address of first argument
movzx eax, byte [ebx] ; First character, is e.g. "3"
sub al, "0" ; Convert from "3" -> 3
imul eax, 10 ; EAX now holds 3 * 10 == 30
mov dl, byte [ebx + 1] ; Second character, is e.g. "5"
sub dl, "0" ; Convert from "5" -> 5
add al, dl ; EAX now holds 3 * 10 + 5 == 35
call print_int ; Prints "35"