如何使用NASM查找字符串的长度? [英] How would I find the length of a string using NASM?
问题描述
我正在尝试使用NASM编写一个程序,该程序从命令行参数中获取输入.由于未提供字符串长度,因此我试图制作一个函数来计算自己的字符串.这是我的尝试,它使用指向ebx
寄存器中的字符串的指针,并返回ecx
中的字符串的长度:
I'm trying to make a program using NASM that takes input from command line arguments. Since string length is not provided, I'm trying to make a function to compute my own. Here is my attempt, which takes a pointer to a string in the ebx
register, and returns the length of the string in ecx
:
len:
push ebx
mov ecx,0
dec ebx
count:
inc ecx
inc ebx
cmp ebx,0
jnz count
dec ecx
pop ebx
ret
我的方法是逐个字符地检查字符串,然后检查它是否为空.如果不是,我增加ecx
并转到下一个字符.我相信问题是cmp ebx,0
对于我正在尝试的操作是不正确的.如何正确检查字符是否为空?另外,还有其他我可以做得更好的事情吗?
My method is to go through the string, character by character, and check if it's null. If it's not, I increment ecx
and go to the next character. I believe the problem is that cmp ebx,0
is incorrect for what I'm trying to do. How would I properly go about checking whether the character is null? Also, are there other things that I could be doing better?
推荐答案
您正在将ebx
中的值与0进行比较,这不是您想要的. ebx
中的值是内存中字符的地址,因此应像这样取消引用:
You are comparing the value in ebx
with 0 which is not what you want. The value in ebx
is the address of a character in memory so it should be dereferenced like this:
cmp byte[ebx], 0
此外,最后一个push ebx
应该是pop ebx
.
Also, the last push ebx
should be pop ebx
.
这篇关于如何使用NASM查找字符串的长度?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!