【发布时间】:2015-11-04 04:24:59
【问题描述】:
我正在做一个项目,我们需要将 char 类型的数组作为参数传递并反转数组。我觉得我非常接近完成它,但我被困在实际的交换过程中。
对于我的 .asm 中的交换功能,我使用了与 c++ 中相同的方法(使用未使用的寄存器作为临时寄存器,然后交换正面和背面。)我不明白的是我将如何进行更改该地址的实际内容。我假设执行以下操作会“更改”目标地址的内容:
mov eax,[edx]
但是,这并没有按计划进行。在我运行 for 循环再次遍历数组后,一切都保持不变。
如果有人能指出我正确的方向,那就太好了。我已经为下面的代码提供了尽可能多的 cmets。
另外,我在一个 .asm 文件中完成所有这些工作;但是,我的教授希望我为以下每个函数提供 3 个单独的 .asm 文档:swap、reverse 和 getLength。我试图在 reverse.asm 中包含另外 2 个 .asm 文档,但它一直给我一个错误。
汇编代码开始:
.686
.model flat
.code
_reverse PROC
push ebp
mov ebp,esp ;Have ebp point to esp
mov ebx,[ebp+8] ;Point to beginning of array
mov eax,ebx
mov edx,1
mov ecx,0
mov edi,0
jmp getLength
getLength:
cmp ebp, 0 ;Counter to iterate until needed to stop
je setup
add ecx,1
mov ebp,[ebx+edx]
add edx,1
jmp getLength
setup: ;This is to set up the numbers correctly and get array length divided by 2
mov esi,ecx
mov edx,0
mov eax,ecx
mov ecx,2
div ecx
mov ecx,eax
add ecx,edx ;Set up ecx(Length of string) correctly by adding modulo if odd length string
mov eax,ebx
dec esi
jmp reverse
reverse: ;I started the reverse function by using a counter to iterate through length / 2
cmp edi, ecx
je allDone
mov ebx,eax ;Set ebx to the beginning of array
mov edx,eax ;Set edx to the beginning of array
add ebx,edi ;Move ebx to correct index to perform swap
add edx,esi ;Move edx to the back at the correct index
jmp swap ;Invoke swap function
swap:
mov ebp,ebx ;Move value to temp
mov ebx,[edx] ;Swap the back end value to the front
mov edx,[edx] ;Move temp to back
inc edi ;Increment to move up one index to set up next swap
dec esi ;Decrement to move back one index to set up for next swap
jmp reverse ;Jump back to reverse to setup next index swapping
allDone:
pop ebp
ret
_reverse ENDP
END
C++ 代码开始:
#include <iostream>
#include <string>
using namespace std;
extern "C" char reverse(char*);
int main()
{
const int SIZE = 20;
char str1[SIZE] = { NULL };
cout << "Please enter a string: ";
cin >> str1;
cout << "Your string is: ";
for (int i = 0; str1[i] != NULL; i++)
{
cout << str1[i];
}
cout << "." << endl;
reverse(str1);
cout << "Your string in reverse is: ";
for (int i = 0; str1[i] != NULL; i++)
{
cout << str1[i];
}
cout << "." << endl;
system("PAUSE");
return 0;
}
【问题讨论】:
-
您正在使用 Intel 汇编语法。在该语法中,第一个操作数是目标,第二个是源,但反之亦然。
-
由于我对整个括号(即 [edx])感到困惑,因此我假设 [edx] 中的任何内容都将替换 ebx 的内容(当前具有第一个索引的地址)。例如在 C++ 中(因为我更熟悉 C++): int i = 25; int *p = &i; *p = 35;这是我执行 mov ebx,[edx] 时发生的情况吗??
-
在这种情况下
edx指向的内存的32位将被复制到ebx。