Array Indexing in Nasm x86-64

In our previous lesson, we learnt how to use and implement macros to make our Nasm x64 code efficient and non-repetitive.
Arrays Are 0-Indexed (Like Any Real Language 🙂)
In Nasm x64, arrays (including strings) are 0-indexed, just like in C or Python i.e. the first element is accessed at index 0.
Here’s a Python example for context:
arr_string = "Hello Earthlings!"
print(arr_string[0]) # output: H
The following Nasm x64 demonstrates an array indexing similar to the python code above
%include "mymacros.inc"
section .data
newline db 10 ; newline ascii character
arr_string db "Hello Earthling!",0 ; initializing array
section .bss
output resb 3 ; reserving 3 bytes for output
section .text
global _start
_start:
mov rcx, 0 ; set rcx to 0
mov al, [arr_string + rcx] ; [arr + 0] means arr[0] and then move it to al
mov [output], al ; move al value into output
print output, 2
print newline, 1
exit 0
Don’t Do This ❌
One may be inclined to do the following
mov [output], [arr_string + rcx] ; ❌ this is wrong, I repeat, very very wrong
The above is called memory-memory move. It is not allowed in Nasm x86. Hence the reason for an intermediate register, al.
The only moves allowed are
register-register mov rax, rbx
register-memory mov [output], al
memory-register mov al, [output]
So always remember: use an intermediate register (like al, rax, etc.) when moving data from one memory location to another.
Conclusion
Array indexing in Nasm x64 follows the same logic as higher-level languages, but with more control and more responsibility. Remember that you control the registers and memory explicitly, and you must follow the hardware rules; no hand-holding here.
Using mov al, [arr + rcx], gives you full control to walk through a string or array one byte at a time. And that is the real beauty of low-level programming; you see everything that is happening under the hood.
Next time, we’ll look at how to loop through an entire array character by character and determine its length.
Exercise
Toggle the value in rcx with values in the range of 0 to 14 to display different characters.
mov rcx, 5
What character displays now?
Subscribe to my newsletter
Read articles from Rawley Amankwah directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
