这里的一个小问题,试图创建将字符串转换为整数的汇编代码。不幸的是,我找不到它“中断”的原因,我输入54321并将其转换为543418。一切正常,直到2,然后它打印随机数而不是打印相同的54321。我已经花了一个小时进行调试,但是找不到这个问题的原因,也许我是盲人?
#include <stdio.h>
#include <string.h>
#include "stdlib.h"
int main(int argc, char** argv)
{
int result;
char* argv1 = argv[1];
if (argc < 2)
{
printf("Parameter is not provided*/\n");
return(0);
}
__asm
{
push eax
push ebx
push ecx
mov ecx, argv1 // 54321 --> 5 *10+4=54 *10+3=543 *10+2=5432 *10+1=54321
mov ebx, 10 // register in which i put value
mov al, byte ptr[ecx] // byte of string to al
sub al, '0'
loop_begins:
mov dl, byte ptr [ecx] // byte of string to dl
cmp dl, 0 // compare to zero (string end)
je loop_ends // if zero byte (string end)
// here we make char out of int
xor edx, edx // zero edx
mul ebx // edx: eax = eax * ebx
inc ecx // ecx points to next char in string
mov dl, byte ptr [ecx] // dl - edx part, other register
sub dl, '0' // same, but other element
add eax, edx // addition (here we get 54)
xor edx, edx // zero edx
jmp loop_begins // and loop to next char
loop_ends:
mov [result], eax // answer to variable result
pop ecx
pop ebx
pop eax
};
printf("Answer is %d\n", result);
system("PAUSE");
}
答案 0 :(得分:0)
我对您的代码进行了一些修改(在注释中<mod>
),以保持您的精神(还根据我的弱点和长期未使用的asm
知识):
__asm
{
push eax // current value / result
push ebx // 10
push ecx // string
xor eax, eax // <mod> : reset eax
mov ebx, 10 // register in which i put value
mov ecx, argv1 // 54321 --> 5 *10+4=54 *10+3=543 *10+2=5432 *10+1=54321
// <mod> : unnecessary
// mov al, byte ptr[ecx] // byte of string to al
// sub al, '0'
loop_begins:
mov dl, byte ptr [ecx] // byte of string to dl
cmp dl, 0 // compare to zero (string end)
je loop_ends // if zero byte (string end)
// here we make char out of int
// xor edx, edx // zero edx // <mod> : unnecessary
mul ebx // edx: eax = eax * ebx
mov dl, byte ptr [ecx] // dl - edx part, other register
sub dl, '0' // same, but other element
add eax, edx // addition (here we get 54)
// xor edx, edx // zero edx // <mod> : unnecessary
inc ecx // ecx points to next char in string // <mod> moved as suggested in comments
jmp loop_begins // and loop to next char
loop_ends:
mov [result], eax // answer to variable result
pop ecx
pop ebx
pop eax
};