Assembly 汇编x86 32位/反向和追加字符串
我想反转组件x-86中的字符串。意思-如果我得到“1234”,我希望我的结果是“4321”。我想把每个字符推到堆栈中,然后弹出它们。但我不知道该怎么做,我需要一个缓冲区?(我可以覆盖原始字符串)。您可以使用一种抽象数据类型(例如堆栈或队列)来实现这一点,但为什么要麻烦呢 只需使用两个指针,一个在起点,一个在终点,然后交换它们指向的内容。增加起始指针,减少结束指针,然后继续运行,直到它们相遇或交叉 在下面的代码中(伪代码,因为(1)这听起来有点像家庭作业,(2)它很容易转换为任何过程语言),我将假设使用C风格的字符串,但您可以很容易地调整其他变体。假设您有权访问第一个字符的Assembly 汇编x86 32位/反向和追加字符串,assembly,x86,x86-64,Assembly,X86,X86 64,我想反转组件x-86中的字符串。意思-如果我得到“1234”,我希望我的结果是“4321”。我想把每个字符推到堆栈中,然后弹出它们。但我不知道该怎么做,我需要一个缓冲区?(我可以覆盖原始字符串)。您可以使用一种抽象数据类型(例如堆栈或队列)来实现这一点,但为什么要麻烦呢 只需使用两个指针,一个在起点,一个在终点,然后交换它们指向的内容。增加起始指针,减少结束指针,然后继续运行,直到它们相遇或交叉 在下面的代码中(伪代码,因为(1)这听起来有点像家庭作业,(2)它很容易转换为任何过程语言),我将假
地址值,则以下伪代码就足够了:
set pstart to address of first character
# Locate last character
set pend to pstart
while [pend] is not null:
pend = pend + 1
pend = pend - 1
# Continue until they cross
while pstart < pend:
# Swap contents
tmp = [pstart]
[pstart] = [pend]
[pend] = tmp
# Move pointers
pstart = pstart + 1
pend = pend - 1
您可以使用一种抽象数据类型(例如堆栈或队列)来实现这一点,但为什么要这么麻烦呢
只需使用两个指针,一个在起点,一个在终点,然后交换它们指向的内容。增加起始指针,减少结束指针,然后继续运行,直到它们相遇或交叉
在下面的代码中(伪代码,因为(1)这听起来有点像家庭作业,(2)它很容易转换为任何过程语言),我将假设使用C风格的字符串,但您可以很容易地调整其他变体。假设您有权访问第一个字符的地址值,则以下伪代码就足够了:
set pstart to address of first character
# Locate last character
set pend to pstart
while [pend] is not null:
pend = pend + 1
pend = pend - 1
# Continue until they cross
while pstart < pend:
# Swap contents
tmp = [pstart]
[pstart] = [pend]
[pend] = tmp
# Move pointers
pstart = pstart + 1
pend = pend - 1
类似的方法可以工作(假设32位模式,使用NASM语法编写):
类似的方法可以工作(假设32位模式,使用NASM语法编写):
不确定你是如何追踪原始字符串的,但我在很久以前做过类似的事情。最简单的(但不是速度最优的)方法是,假设你正在接受键盘输入,使用一个缓冲区,用默认的方向标志将SB放入缓冲区,然后在输入完成后,翻转方向标志,设置寄存器,然后lodsb。。。根据您的字符串来自何处,根据需要进行调整。不确定如何跟踪原始字符串,但我早就做了类似的事情。最简单的(但不是速度最优的)方法是,假设你正在接受键盘输入,使用一个缓冲区,用默认的方向标志将SB放入缓冲区,然后在输入完成后,翻转方向标志,设置寄存器,然后lodsb。。。根据字符串的来源进行必要的调整。是否使用二进制?意思是1234=10011010010?如果是,则您可以将函数RoR(向右旋转)用于32位符号16次您是否使用二进制?意思是1234=10011010010?如果是,则可以将函数RoR(向右旋转)用于32位表示法16次
; finding string length:
mov ebx, mystr ; current position within the string
mov ecx, 0 ; current string length
l1:
mov al, [ebx] ; fetch a character from the string
cmp al, 0 ; is this string end?
je l2 ; yes, it is
inc ebx ; increment the position from where we'll read next character
inc ecx ; increment length
jmp l1 ; repeat
l2: ; ecx = string length
; reversing the string:
cmp ecx, 2 ; is the string too short?
jb l4 ; yes, it has 0 or 1 chars, we're done
mov ebx, mystr ; ebx points to the first char in the string
lea edx, [ebx+ecx-1] ; edx = ebx+ecx-1 - points to the last char in the string
shr ecx, 1 ; ecx = half the string length
l3:
mov al, [ebx]
xchg al, [edx]
mov [ebx], al ; [ebx] and [edx] swapped
inc ebx ; advance head pointer
dec edx ; advance tail pointer
loop l3 ; decrement ecx and if ecx isn't 0, repeat
l4:
;...
; string (NULL-terminated):
mystr db '1','2','3','4',0