From 5685ac6e67960f729c05e3952d0a252a687ca846 Mon Sep 17 00:00:00 2001 From: Kris Lamoureux Date: Tue, 7 Oct 2025 20:29:32 -0400 Subject: [PATCH] Calculate string length --- helloworld.asm | 30 +++++++++++++++++++++++------- 1 file changed, 23 insertions(+), 7 deletions(-) diff --git a/helloworld.asm b/helloworld.asm index 05f35b2..63087e8 100644 --- a/helloworld.asm +++ b/helloworld.asm @@ -4,17 +4,33 @@ ; Run with: ./helloworld SECTION .data -msg db 'Hello World!', 0Ah ; assign msg variable with your message string +msg db 'Hello, brave new world!', 0Ah ; assign msg variable with your message string SECTION .text global _start _start: - mov edx, 13 ; number of bytes to write - one for each letter plus 0Ah (line feed character) - mov ecx, msg ; move the memory address of our message string into ecx - mov ebx, 1 ; write to the STDOUT file - mov eax, 4 ; invoke SYS_WRITE (kernel opcode 4) + mov ebx, msg ; move the address of our message string into EBX + mov eax, ebx ; move the address in EBX into EAX as well (Both now point to the same segment in memory) + +nextchar: + cmp byte [eax], 0 ; compare the byte pointed to by EAX at this address against zero (Zero is an end of string delimiter) + jz finished ; jump (if the zero flagged has been set) to the point in the code labeled 'finished' + inc eax ; increment the address in EAX by one byte (if the zero flagged has NOT been set) + jmp nextchar ; jump to the point in the code labeled 'nextchar' + +finished: + sub eax, ebx ; subtract the address in EBX from the address in EAX + ; remember both registers started pointing to the same address (see line 15) + ; but EAX has been incremented one byte for each character in the message string + ; when you subtract one memory address from another of the same type + ; the result is number of segments between them - in this case the number of bytes + + mov edx, eax ; EAX now equals the number of bytes in our string + mov ecx, msg ; move the memory address of our message string into ecx + mov ebx, 1 ; write to the STDOUT file + mov eax, 4 ; invoke SYS_WRITE (kernel opcode 4) int 80h - mov ebx, 0 ; return 0 - mov eax, 1 ; SYS_EXIT + mov ebx, 0 ; return 0 + mov eax, 1 ; SYS_EXIT int 80h