dw - Define Word
Part of the Fundamentals section of Coddy's Assembly journey — lesson 25 of 45.
db creates one byte of data. But sometimes you need to store larger numbers that do not fit in a single byte (0-255). For that, you use dw — Define Word.
A word in x86 assembly is 2 bytes (16 bits).
Syntax:
label dw valuelabel— the name you give to this memory addressdw— Define Word directivevalue— the number to store (0 to 65,535)
Examples:
section .data
smallNum dw 1000 ; 2 bytes, value 1000
bigNum dw 65535 ; 2 bytes, maximum value (all bits 1)
price dw 499 ; 2 bytes, value 499What you can store in one word (2 bytes):
| Type | Range | Example |
|---|---|---|
| Small to medium number | 0 to 65,535 | dw 32000 |
| Memory offset (16-bit) | 0 to 65,535 | dw 0x7FFF |
Multiple words on one line:
section .data
values dw 100, 200, 300, 400 ; Creates 4 words (8 bytes total)How to use a word in your code:
Since a word is 2 bytes, you use the 16-bit register ax (not al):
section .data
myWord dw 1000
section .text
mov ax, [myWord] ; Load the value 1000 into ax
add ax, 500 ; ax becomes 1500
mov [myWord], ax ; Store 1500 back into myWordComparison: db vs dw
| Directive | Size | Range | Register to use |
|---|---|---|---|
db | 1 byte | 0 to 255 | al |
dw | 2 bytes | 0 to 65,535 | ax |
Challenge
EasyCreate a word called population with the value 25000 in the .data section.
Try it yourself
%include "data.asm"
section .data
msg db 'population = '
msg_len equ $ - msg
newline db 0xa
section .bss
buffer resb 16
section .text
global _start
_start:
; Load the word value into ax
mov ax, [population]
; Convert ax to decimal string
mov rsi, buffer
add rsi, 15 ; Go to end of buffer
mov byte [rsi], 0 ; Null terminator
mov cx, 10 ; Divisor for decimal conversion
convert_loop:
xor dx, dx ; Clear dx for division
div cx ; Divide ax by 10, ax = quotient, dx = remainder
add dl, '0' ; Convert remainder to ASCII
dec rsi
mov [rsi], dl ; Store digit
cmp ax, 0
jnz convert_loop
; Save digit pointer and length BEFORE they get clobbered
mov r8, rsi ; r8 = pointer to first digit
mov r9, buffer
add r9, 15
sub r9, rsi ; r9 = number of digits
; Print message
mov rax, 1
mov rdi, 1
mov rdx, msg_len
mov rsi, msg
syscall
; Print the number
mov rax, 1
mov rdi, 1
mov rsi, r8
mov rdx, r9
syscall
; Print newline
mov rax, 1
mov rdi, 1
mov rsi, newline
mov rdx, 1
syscall
; Exit
mov rax, 60
mov rdi, 0
syscall
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Fundamentals
1The Machine
What is CPUMemoryRegisters vs MemoryHow instructions workTwo-File PatternThe x86-64 Architecture4Data Definition
The .data Sectiondb - Define Bytedw - Define Worddd - Define Double Worddq - Define Quad WordStrings with dbThe $ SymbolRecap: Build data.asm