I want to know another way to count character of a string not use 0Ah/int21h. Thank for your help :D
Asked
Active
Viewed 4,826 times
1
-
http://stackoverflow.com/search?q=%5Bassembly%5D+strlen – Peter Cordes Oct 24 '16 at 12:49
-
Write some code to do it yourself? That's a super approach. – David Hoelzer Oct 24 '16 at 21:59
1 Answers
1
Start with a register pointing to the first character of the string and another register set to zero.
Loop until the contents of the first register are the NUL
character (or whatever terminator you want), incrementing both those registers.
At the end, the second register will have the length.
In pseudo-asm-code (since it's very likely this is classwork):
push r1, r3 ; preserve registers
load r1, address-of-string
xor r2, r2 ; xor a number with itself gives 0
startloop:
load r3, [r1] ; get memory contents
beq endloop ; if NUL, we're at string end
inc r1 ; otherwise incr both and loop back
inc r2
bra startloop
endloop:
pop r3, r1 ; restore registers
; r2 now has the length.
Your job is to now turn that into real assembly code (most likely x86 given your mention of int 21h
).

paxdiablo
- 854,327
- 234
- 1,573
- 1,953
-
yeah it's my homework :D i try to find out another way but my code is too long. tks you again – Hoàng Minh Toàn Oct 24 '16 at 12:24
-
BTW, `xor same,same` is only a good zeroing idiom on x86. On many other architectures, including ARM, [it's architecturally required to carry a dependency on the input register (to preserve memory_order_consume semantics)](http://stackoverflow.com/questions/37222999/convert-c-to-assembly-with-predicated-instruction/37224546#comment61983585_37224546), so `mov r2, 0` is the same size (or smaller on ARM Thumb2) and significantly better. But clearly you were just trying to write x86 asm in disguise, so +1 :) – Peter Cordes Oct 24 '16 at 13:15