gpt4 book ai didi

assembly - 在汇编中反转字符串时遇到问题

转载 作者:行者123 更新时间:2023-12-02 19:10:33 24 4
gpt4 key购买 nike

我正在尝试反转汇编中的字符串。但是我的代码似乎无法正常工作。我添加了一个换行符字符串以提高可读性。

我使用linux和nasm作为编译器。

我认为如果我获取地址指针的值并将它们切换到正确的位置,字符串最终会被反转,然后恢复正常。

这是我的代码:

section .data
hello db 'Hello world!'
helloLen equ $-hello
derp db '=========',10
derplen equ $-derp

section .text
global main

main:
mov eax,0
mov ecx,helloLen

reverse:
;move pointer
mov ebx,hello
add ebx,eax
push eax

;move pointer
mov eax,hello
add eax,ecx
push ecx

;switch bytes
push ebx
mov ebx,[ebx]
mov [eax],ebx
pop ebx
mov eax,[eax]
mov [ebx],eax

;print text
mov eax,4
mov ebx,1
mov ecx,hello
mov edx,helloLen
int 80h

;Print newline
mov eax,4
mov ebx,1
mov ecx,derp
mov edx,derplen
int 80h

;increment and decrement
pop ecx
dec ecx
pop eax
inc eax

cmp eax,helloLen
jne reverse

end:
mov eax,1
mov ebx,0
int 80h

这是我得到的输出:

Hello world!Hell=====
Hello worldellol=====
Hello worlllo ol=====
Hello worlo w ol=====
Hello woo wow ol=====
Hello wooooow ol=====
Hello wooooow ol=====
Helloooooooow ol=====
Helloooooooow ol=====
Helooowooooow ol=====
Heoow wooooow ol=====
How o wooooow ol=====

最佳答案

通过交换字符来反转字符串的方法是交换第一个和最后一个,然后交换第二个和倒数第二个,等等。在 C 中,你可以这样写:

for (i = 0; i < len/2; ++i)
{
c = s[i];
s[i] = s[len-i-1];
s[len-i-1] = c;
}

在汇编语言中,最简单的方法是设置ESI和EDI寄存器指向字符串的开头和结尾,然后循环。在每次迭代中,您都会增加 ESI 并减少 EDI。结果看起来像这样:

mov ecx, helloLen
mov eax, hello
mov esi, eax ; esi points to start of string
add eax, ecx
mov edi, eax
dec edi ; edi points to end of string
shr ecx, 1 ; ecx is count (length/2)
jz done ; if string is 0 or 1 characters long, done
reverseLoop:
mov al, [esi] ; load characters
mov bl, [edi]
mov [esi], bl ; and swap
mov [edi], al
inc esi ; adjust pointers
dec edi
dec ecx ; and loop
jnz reverseLoop

关于assembly - 在汇编中反转字符串时遇到问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13587313/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com