Assembly 将转换后的数字追加到现有字符串
我使用了一个简单的算法将数字转换为字符串,我根据自己的目的对其进行了调整,但它并不能完全满足我的需要。 我有一个字符串:Assembly 将转换后的数字追加到现有字符串,assembly,Assembly,我使用了一个简单的算法将数字转换为字符串,我根据自己的目的对其进行了调整,但它并不能完全满足我的需要。 我有一个字符串: string point, "xxx points" 和常数: const10 dd 10 points dd 50 ; range from 0 - 990 调整后的例行程序 mov eax, [points] ; number to be converted .convNum: push eax push edx
string point, "xxx points"
和常数:
const10 dd 10
points dd 50 ; range from 0 - 990
调整后的例行程序
mov eax, [points] ; number to be converted
.convNum:
push eax
push edx
xor edx,edx
div dword [const10] ;eax = result, edx = remainder
cmp eax, dword 0 ; test of the res
je .print
jmp .convNum
.print:
lea eax,[edx+'0']
mov [point], dword eax ; need to replace xxx in string by number
pop edx
pop eax
这一个没有按预期工作,因为它只显示一个数字,我理解,但我无法以我想要的方式更改例程。
编辑:
添加另一版本的代码
push eax
push edx
mov eax, [points]
.convNum:
xor edx,edx
div dword [const10]
lea eax,[edx+'0']
mov ecx,[counter]
cmp ecx, 1
jne .next
mov [point+2], byte al
mov eax,[points]
div dword [const10]
jmp .again
.next:
cmp ecx, 2
jne .next2
mov [point+1], byte al
mov eax,[points]
div dword [const10]
div dword [const10]
jmp .again
.next2:
mov ecx,[p_bodu]
cmp ecx, 100
jb .kend
mov [point], byte al
jmp .kend
.again:
inc ecx
mov [counter],ecx
jmp .convNum
.kend:
pop edx
pop eax
此代码将数字从最低到最高。像120这样的数字转换得很好,但像130150这样的数字转换成630650,同样地,像140这样的数字转换得很好,你继续在一个循环中推动EAX和EDX。你只需要做一次 将.convNum标签向下移动2行:
mov eax, [points] ; number to be converted
push eax
push edx
.convNum:
xor edx,edx
div dword [const10] ;eax = result, edx = remainder
cmp eax, dword 0 ; test of the res
jne .convNum
.print:
还要注意,您应该写入字节而不是dword:
mov [point], al ;
您编写的代码将只处理所提供值的最高位数。要继续检索较低位置的数字,您需要从数字中减去当前数字乘以(10的倍数),然后重复代码。因此您需要替换“xxx”。添加空格(“xxx”)后,您需要替换适合32位寄存器的4个字节(=1个dword)。寄存器将存储为“little endian”。如果将0x20303531存储到内存中,它将显示为0x31 0x35 0x30 0x20,这是“150”的ASCII代码 以下是NASM的一个示例:
SECTION .data
point db "xxx points", 0
const10 dd 10
points dd 150 ; range from 0 - 990
SECTION .text
...
mov ebx, 0x20202020 ; 4 spaces
mov eax, [points] ; number to be converted
.convNum:
xor edx,edx
div dword [const10] ; eax = result, edx = remainder
shl ebx, 8 ; shift last result
mov bl, dl ; copy remainder to the last byte of EBX
or bl, '0' ; to ASCII
test eax, eax ; test of the res
je .print
jmp .convNum
.print:
mov [point], ebx ; need to replace xxx in string by number
...
我无法发布完整的程序,因为我不知道您的操作系统。您是对的,但是输出不会改变。在您意识到此代码的目的是仅提取所提供数字的最高位数后,字符串仅附加数字
5
而不是0
?以较低的数字减法(数字*10)继续并重复代码!你要找的词不是“正当的”。没错,我会编辑post@rkhb非常好的解决方案。(+1)但是为什么要浪费一个额外的jmp
而不编写testeax,eax
jne.convNum
@Fifoernik:因为我想尽可能接近OP的原始版本。我总是认为MCVE只是更大程序的一部分,无论如何,这样的事情都有其相关性。