Menu
Coddy logo textTech

Byte Count (rdx)

Part of the Fundamentals section of Coddy's Assembly journey — lesson 38 of 45.

You have told the OS where to print (rdi) and what to print (rsi). Now you need to tell it how many bytes to print.

The register for byte count is rdx.

Why does the OS need the length?

The OS does not know where your string ends. Without a length, it would keep reading memory forever. The length tells the OS exactly when to stop.

Example:

section .data
    msg db 'Hello', 0x0a
    msgLen equ $ - msg

section .text
    mov rdx, msgLen      ; rdx = number of bytes to print

What happens if the length is wrong?

If you setResult
Too shortOnly part of the string prints
Too longThe OS keeps reading past your string into garbage memory — may print random characters or crash
ZeroNothing prints

Calculating length automatically:

You already learned the $ - label pattern in Chapter 3:

section .data
    msg db 'Hello', 0x0a
    msgLen equ $ - msg    ; msgLen = 6 (Hello + newline)

This ensures the length is always correct, even if you change the string.

Complete example:

section .data
    msg db 'Hello', 0x0a
    msgLen equ $ - msg

section .text
    mov rax, 1           ; write syscall
    mov rdi, 1           ; stdout
    mov rsi, msg         ; address of string
    mov rdx, msgLen      ; number of bytes
    syscall
challenge icon

Challenge

You are given a string called color with the value 'Red' followed by a newline. A constant called colorLen has already been defined using $ - color.

Write the line of code that sets rdx to the length of the string using the colorLen constant.

Only write the mov instruction for rdx.

Try it yourself

section .text
    global _start

_start:
    ; Student's code runs first (sets rdx)
    %include "solution.asm"
    
    mov rax, 1
    mov rdi, 1
    mov rsi, color
    ; rdx already has the length (from student's code)
    syscall

    mov rax, 60
    mov rdi, 0
    syscall
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Fundamentals