Loop Summation (1..N)
Sum integers 1..N with a counted loop using dec/jnz.
Code
; sum_to(N) -> 1+2+...+N rdi=N, result in rax
section .text
global sum_to
sum_to:
xor eax, eax ; accumulator = 0
test edi, edi
jle .done ; if N <= 0, return 0
.loop:
add eax, edi ; accumulate N, N-1, ...
dec edi
jnz .loop ; repeat until edi == 0
.done:
ret
; Faster closed form: sum(N) = N*(N+1)/2
global sum_to_fast
sum_to_fast:
mov eax, edi
add eax, 1 ; N+1
imul eax, edi ; N*(N+1)
shr eax, 1 ; /2
retExplanation
The loop uses dec/jnz instead of the slower 'loop' instruction. Working in 32-bit (eax/edi) keeps the encoding small and is enough for moderate N. The second version uses the closed-form N*(N+1)/2 — compilers often do this transformation (loop strength reduction) and it's O(1) instead of O(N). shr by 1 is the same as unsigned /2.
More Assembly Snippets
Hello World via Linux syscall
A freestanding x86-64 program that prints and exits using only kernel syscalls.
Function Call Convention (System V AMD64)
Pass args in registers, preserve callee-saved regs, keep rsp 16-byte aligned.
strlen — Scan Until NUL
Compute C-string length by scanning memory until a zero byte.
memcpy — Copy with rep movsb
Use the rep movsb string instruction for a tight memory copy.
Bit Manipulation: popcount, ctz, abs
Use BMI/ABM instructions for branchless bit operations.
Read a File via syscalls
open/read/write/close a file using only Linux syscalls.