Last Updated: 2023-07-21 14:25:43 Friday
-- TOC --
给自己出了一道题:通过命令行传入一个数字字符串,这一个signed数字,前面可以有正负号,但正号可以省略,将输入字符串转signed数字,其装入一个64位的寄存器中,最后打印输出。以signed的方式解释64位寄存器中的数字!
代码如下:
.intel_syntax noprefix
.section .rodata
err_msg:
.asciz "parameter error!"
overflow_msg:
.asciz "overflow!"
end_show:
.asciz "%ld : 0x%lX\n"
.global main
.text
main:
sub rsp, 8
cmp rdi, 2
jnz param_error
xor rax, rax
mov r10, [rsi+8]
xor ecx, ecx
mov cl, BYTE PTR [r10]
cmp ecx, 0x2D # if '-'
jz negative
mov QWORD PTR [rsp], 0 # +
cmp ecx, 0x2B # if '+'
jz positive
jmp loop
negative:
mov QWORD PTR [rsp], 1 # -
positive:
inc r10
loop:
xor ecx, ecx
mov cl, BYTE PTR [r10]
test ecx, ecx
jz normal_end
cmp ecx, 0x30
jb param_error
cmp ecx, 0x39
ja param_error
sub ecx, 0x30
imul rax, 10
add rax, rcx
js check_max_neg
inc r10
jmp loop
check_max_neg:
cmp QWORD PTR [rsp], 0
jz overflow
dec rax
js overflow
inc rax
jmp real_end
normal_end:
cmp QWORD PTR [rsp], 0
jz real_end
neg rax
real_end:
mov rdi, OFFSET end_show
mov rsi, rax
mov rdx, rax
xor eax, eax
call printf
add rsp, 8
xor eax, eax
ret
param_error:
mov rdi, OFFSET err_msg
call puts
add rsp, 8
mov eax, 1
ret
overflow:
mov rdi, OFFSET overflow_msg
call puts
add rsp, 8
mov eax, 2
ret
运行效果如下:
$ ./c2n 123
123 : 0x7B
$ ./c2n -123
-123 : 0xFFFFFFFFFFFFFF85
$ ./c2n 9223372036854775807
9223372036854775807 : 0x7FFFFFFFFFFFFFFF
$ ./c2n 9223372036854775808
overflow!
$ ./c2n -9223372036854775808
-9223372036854775808 : 0x8000000000000000
$ ./c2n +9223372036854775807
9223372036854775807 : 0x7FFFFFFFFFFFFFFF
Nice...:)
本文链接:https://cs.pynote.net/hd/asm/202307041/
-- EOF --
-- MORE --