Assembly String Length Explained
Assembly String Length Explained
.model small
Declares a small memory model (separate 64KB segments for code and data).
.stack 100h
Allocates 256 bytes for the stack.
.data
Start of data segment.
str db 'Hello, World!$', 0
String to print, '$' is the DOS terminator.
msgLen db 13, 10, 'Length = $'
Message with newline followed by 'Length ='.
len db 0
Variable to store string length.
buffer db 5 dup(?)
Buffer to store digits (not used directly here).
.code
Start of code segment.
main:
Program entry point.
mov ax, @data
Load data segment address into AX.
mov ds, ax
Initialize DS to point to data segment.
lea si, str
Load address of string into SI.
xor cx, cx
Clear CX to use for character count.
count_loop:
Loop label to iterate over the string.
mov al, [si]
Load current character.
cmp al, '$'
Compare with '$' terminator.
je end_count
Jump to end if terminator is found.
inc cx
Increment character counter.
inc si
Move to next character.
jmp count_loop
Repeat loop.
end_count:
Label after string end is found.
mov len, cl
Store character count in 'len'.
mov ah, 09h
DOS function to print string.
lea dx, str
Load address of string.
int 21h
Print the string.
mov ah, 09h
DOS function to print message.
lea dx, msgLen
Load address of 'Length =' message.
int 21h
Print the message.
mov ax, 0
Clear AX.
mov al, len
Move string length into AX.
call PrintNumber
Call number printing subroutine.
mov ah, 4Ch
DOS exit function.
int 21h
Terminate program.
PrintNumber:
Subroutine to print number in AX.
mov cx, 0
Clear digit count.
.convert:
Start of number conversion loop.
xor dx, dx
Clear DX before division.
mov bx, 10
Divide by 10 to extract digits.
div bx
Divide AX by BX; remainder in DX.
add dl, '0'
Convert digit to ASCII.
push dx
Push digit to stack.
inc cx
Increment digit count.
cmp ax, 0
Check if all digits processed.
jne .convert
Repeat if digits remain.
.print_loop:
Start of digit printing loop.
pop dx
Pop digit from stack.
mov ah, 02h
DOS function to print character.
int 21h
Print digit.
loop .print_loop
Repeat for all digits.
ret
Return from subroutine.
end main
End of program.