AArch64 Playgroundpractice
05 · practice
Exercises
In a coding exercise, Check runs your program and compares its result with what the exercise asks for. Theory sets are quizzes and short questions, graded on the page. Both follow the course from the first week to the last.
code
Coding exercises
Write the program. The emulator runs it and checks the result, never a stored solution.
68 exercises
binary arithmetic· 3
- 5.1Base eight, by handPrint a number in octal (base 8) without letting
printfdo the conversion: no%oor%loanywhere in the program.core - 5.2The overflow detectiveA 32-bit add can go wrong in two different ways, and the flags record both:core
- 5.3Fibonacci past the horizon
fib(93)is the last Fibonacci number that fits in 64 bits, read as unsigned. This program goes on tofib(186)by keeping each number in...challenge
- 5.1Base eight, by handPrint a number in octal (base 8) without letting
armv8 basics· 4
- 5.4The macro that ate my messageThis program reads a ticket count and a price in cents, multiplies them, and prints the bill on one line. With the input
3 125it should p...intro - 5.5Halfword by halfwordA locker's 64-bit code is
0xbeefcafef00dffff. Build it incode_r; the starter then adds a numbernread from input and prints the code...intro - 5.6Warm up the registersThree values arrive on input, and the starter has already read them into the registers
a_r,b_r, andc_r. Compute(a + b) - cand pr...intro - 5.7Change for a twentyA customer pays with a twenty-dollar bill, 2000 cents. The starter reads the price in cents, from 0 to 2000. Work out the change, then split...core
- 5.4The macro that ate my messageThis program reads a ticket count and a price in cents, multiplies them, and prints the bill on one line. With the input
branching· 3
- 5.8The absolute truthThe starter reads one signed number into the value register. Print its magnitude:
-42prints as42.intro - 5.9Pick the bigger oneTwo contenders arrive on input, and the starter reads them into registers. Print the larger one.intro
- 5.10Rock, paper, scissors refereeReferee one round of rock, paper, scissors. The input holds two moves, player 1's and then player 2's, each written as a number:
0for roc...core
- 5.8The absolute truthThe starter reads one signed number into the value register. Print its magnitude:
loops· 11
- 5.11The overeager counterThis countdown should print
ndown to1, one number per line, and stop. Run it with the5in the stdin box and look closely at the out...intro - 5.12Count by sevensPrint every multiple of seven from 7 up to and including a limit, one per line. The starter reads the limit and holds the first multiple and...intro
- 5.13Collatz countdownStart from a whole number n. If n is even, halve it; if it is odd, make it 3n + 1. Repeat, and n always seems to reach 1 in the end (nobody...core
- 5.14Sum from one to nWrite a loop that adds up every integer from 1 to
nand prints the total.core - 5.15gcd, the Euclid wayEuclid noticed around 300 BC that the greatest common divisor of two numbers does not change when you replace the larger with the remainder...core
- 5.16Fibonacci goes largeCompute the
nth Fibonacci number for thenthe starter reads. With the 50 in the stdin box the answer is 12,586,269,025, which does not...core - 5.17Guess the numberTwo players, one input. The first number is the secret (player 1 types it while player 2 looks away), and every number after it is one of pl...core
- 5.18Fix the loop boundThis program should compute
nfactorial, the product1 * 2 * ... * n, for thenit reads, and print it. Withnset to 5 it runs and...core - 5.19The multiplication tablePrint the
n-by-nmultiplication table, rows ofrow * colpadded into neat columns. The starter readsn.core - 5.20Fizzbuzz, by handThe classic interview question, on a machine with no remainder instruction: print the numbers 1 through a limit, except say
fizzfor multi...core - 5.21Reverse the digitsRead a number and print it with its digits reversed:
9317prints as7139.core
- 5.11The overeager counterThis countdown should print
bitwise· 9
- 5.22Power of two, or not?A power of two (1, 2, 4, 8, and so on) has exactly one bit set. Subtracting 1 clears that bit and sets every bit below it, so
nand...intro - 5.23The secret handshakeTwo friends send each other a secret handshake as a number. Only the low five bits count:core
- 5.24Bit population censusHow many bits of a 64-bit value are set to 1? The starter reads the value in hex (
b7a5in the stdin box). Count them with a loop.core - 5.25Nibbles trade placesA nibble is four bits: half a byte, and exactly one hex digit. Swapping the two nibbles of
0xa7gives0x7a.intro - 5.26Double, double, doubleMultiplying by a power of two never needs a multiply: shifting left by one bit doubles a value, and doing it three times multiplies by eight...intro
- 5.27Unpack the pixelA 32-bit colour packs four 8-bit channels into one word, laid out
0xAARRGGBB: alpha (how solid the pixel is) in the top byte, then red, th...core - 5.28Binary broadcastPrint a byte the way the machine sees it: eight binary digits, so
99prints as01100011. The starter reads the value, from 0 to 255.core - 5.29Machine code detectiveA 32-bit instruction word arrives on standard input in hex. If it is an add or subtract between registers (the shifted-register format), tak...core
- 5.30Assemble it yourselfBe the assembler for one instruction:
add xD, xN, imm, a 64-bit add with an immediate. Standard input gives D, N and the immediate; build...challenge
- 5.22Power of two, or not?A power of two (1, 2, 4, 8, and so on) has exactly one bit set. Subtracting 1 clears that bit and sets every bit below it, so
arrays· 6
- 5.31Rotate by kThe starter reads a number k, and
ringin.dataholds eight words. Rotateringleft by k places, in place, before the print loop shows...core - 5.32Tic-tac-toe judgeThe starter reads a tic-tac-toe board into
boardas one line of nine characters, row by row:X,O, or.for an empty cell. The input...core - 5.33Min-max tournamentFind the smallest and the largest element of an array in one pass, and print both. The starter reads a count and then that many values into...core
- 5.34Sum a global arrayA global array of scores lives in
.bss, and the starter fills it from input: first the count, then that many scores. Add every element and...core - 5.35Bubble up the orderThe starter reads a count and then that many values, in a tangle, into the word array
tangle. Bubble sort them in place, smallest first; t...challenge - 5.36Monster rosterFind the monster with the most hit points in a roster of up to eight, which the starter reads into
roster, an array of structures. Each in...challenge
- 5.31Rotate by kThe starter reads a number k, and
strings· 4
- 5.37Palindrome or notThe starter reads one word of up to 63 letters into
word. Finish it so it says whether the word is a palindrome: a word that reads the sam...core - 5.38Count the vowelsThe starter reads one line of text (the stdin box holds a famous one: it uses every letter of the alphabet). Count its vowels.core
- 5.39Morse code translatorTurn the words on the command line into Morse code. The starter already holds the code for every letter: 26 strings, and a table
morseof...challenge - 5.40Caesar's little secretThe line in the stdin box was encrypted the way Julius Caesar liked it: every lowercase letter shifted three places forward, wrapping around...challenge
- 5.37Palindrome or notThe starter reads one word of up to 63 letters into
memory and the stack· 7
- 5.41The vanishing valueThis program reads two values into registers, swaps them, then prints them in their new order. Run it: one of the values has vanished, and t...core
- 5.42The price is rightThe starter reads a price in cents and a quantity straight into two 32-bit words in
.data,priceandquantity. Multiply them and store...intro - 5.43Which end is up?The starter reads one 32-bit word, typed in hex (for example
12345678), into a local in the stack frame. Print the word's four bytes in th...intro - 5.44Mirror, mirrorThe starter reads a count n (0 to 16) and then n numbers into the word array
listin.bss, and prints the array at the end. Reverse the...core - 5.45Three in a rowRead three integers, keep each one in its own local variable in the stack frame, and print them smallest first on one line.core
- 5.46Stack of platesFour plates go into
main's stack frame, the space on the stack it sets aside for itself, and they come back out top-first. The starter rea...core - 5.47The leaky frameThis program stashes a lucky number from input in its stack frame and prints it back. It should print one line. Run it: the program dies bef...challenge
functions· 2
- 5.48Call yourselfWrite
fact, a subroutine that computes a factorial by calling itself.mainreadsn, callsfact, and printsn! =and the answer.challenge - 5.49The forgetful helper
mainreads a running total intox19and a bonus, asks a helper to double the bonus, and adds the result. With100and20the total s...challenge
- 5.48Call yourselfWrite
subroutines· 4
- 5.50Down to one digit
digsum(n)adds up the decimal digits of n:digsum(1234)is 1 + 2 + 3 + 4 = 10. Apply it again and again and the answer shrinks to one di...core - 5.51Tower of HanoiThree pegs, A, B and C, and a tower of n discs on peg A, the smallest on top. Move the whole tower to peg C one disc at a time, never puttin...challenge
- 5.52Two answers, one callA function hands back one value in x0, but a division has two answers.
divmod(a, b, &q, &r)gets both out: the caller (the code making the...core - 5.53Return to senderA struct bigger than 16 bytes does not fit in x0 and x1, so it comes back another way. The caller, the code making the call, reserves room...challenge
- 5.50Down to one digit
input and output· 6
- 5.54Say it with a frameDraw a box around one word read from input. For the input
hello:intro - 5.55Name tagPrint a name tag from two initials and an age read from input. For the input
A B 19the tag reads:intro - 5.56How many minutes old?Read an age in whole years with
scanfand print how many minutes that is, counting every year as 365 days. For the input19:core - 5.57Echo the sumRead two integers from input with
scanf, add them, and print the total.core - 5.58Count the linesCount the lines and the bytes on standard input without
scanforgetchar: ask the operating system for the bytes yourself with the...core - 5.59High score keeperAn arcade machine keeps its best score in a file called
best.dat, so the record outlives any one game. Standard input gives a count and th...challenge
- 5.54Say it with a frameDraw a box around one word read from input. For the input
command-line arguments· 2
- 5.60Say it louderPrint every command-line argument in capitals, one per line, each followed by
!. Withquiet pleasein the args box the program prints...core - 5.61argv arithmeticEvery number on the command line gets added into one total. The args box under the editor holds four of them; change it and run again, and t...challenge
- 5.60Say it louderPrint every command-line argument in capitals, one per line, each followed by
external data· 2
- 5.62Are these dice loaded?Someone swears their die is fair. Read their rolls and draw a histogram, a bar chart with one bar per face, to check.core
- 5.63Vending machine brainA snack machine sells one thing for 75 cents. It takes nickels (5), dimes (10), quarters (25), loonies (100) and toonies (200), and hands an...challenge
floating point· 5
- 5.64Average temperatureA week of weather readings arrives on standard input: first how many there are, then the temperatures themselves, which can have a fractiona...core
- 5.65Newton's square rootFind the square root of the number in the stdin box without the
fsqrtinstruction, using the rule Isaac Newton's method gives for square r...challenge - 5.66Float anatomyA float read from standard input sits in
s0. Take it apart the way IEEE 754 lays it out, and say what kind of value it is. With the stdin...core - 5.67Build a float from partsRun IEEE 754 backwards: standard input gives a sign (0 or 1), an exponent without its bias, and a fraction in hex. Put them together into a...challenge
- 5.136Four lanes, one addFour players finish a round, and each of them earns the same bonus. The starter reads the four scores and then the bonus (
12 30 7 25and...core
theory
Theory sets
Quizzes, fill-in-the-blank drills, and predict-the-output questions, graded on the page.
68 exercises
system architecture· 5
- 5.68Basic quiz: system architectureCovers the parts of a CPU, volatile and non-volatile memory, what RISC means, the fetch-execute cycle, and comment syntax in AArch64 source.intro
- 5.69Intermediate quiz: system architectureThe machine model behind AArch64 assembly: where code and data live, which instructions are allowed to touch memory, what the system bus car...core
- 5.70Advanced quiz: system architectureRISC versus CISC machine code, where
m4expansion fits into the build, and how a load/store machine moves data between memory and the regi...challenge - 5.71Fill in the blank: system architectureFill in the missing terms: the parts of a CPU, the clock that paces it, the register that tracks execution, and the marker that starts a com...core
- 5.129Basic quiz: CThe C that the assembly lessons start from: type sizes, integer division, copies against addresses, where an array element sits,
printfsp...intro
binary logic· 5
- 5.72Basic quiz: binary logicTwo's complement negation, the sign bit, how many bits one hexadecimal digit carries, what a logical shift left does to a value, and the ins...intro
- 5.73Intermediate quiz: binary logicLogical instructions and their aliases, shifts and sign extension, and the integer widths and number bases behind them.core
- 5.74Advanced quiz: binary logicBitfield insert and extract, arithmetic versus logical shifts, and two's complement negation.challenge
- 5.75Fill in the blank: binary logicFill in the missing mnemonic on each line so it performs the bitwise or shift operation described.core
- 5.76Predict: binary logicFor each shift, mask, and sign-extension snippet, give the exact value left in the destination register.challenge
binary arithmetic· 5
- 5.77Basic quiz: binary arithmeticHow a CPU does integer arithmetic in fixed-size registers: modulus wraparound, subtraction through negation, the meaning of a carry out,...intro
- 5.78Intermediate quiz: binary arithmeticHow fixed-width arithmetic wraps, what a carry out of the most significant bit means, which flags the signed and unsigned branch conditions...core
- 5.79Advanced quiz: binary arithmeticCarry chains for extended-precision values (wider than one register), the shift-and-add multiplication algorithm, and the flag rules behind...challenge
- 5.80Fill in the blank: binary arithmeticFill in the missing mnemonics and condition codes so each instruction performs the arithmetic or the unsigned branch described.core
- 5.81Predict: binary arithmeticTrace a 32-bit add that wraps around, a carry passed from one add to the next, and a signed multiply with a 64-bit result.challenge
armv8 basics· 5
- 5.82Basic quiz: ARMv8 assemblyHow AArch64 splits privilege across exception levels, which registers a call may overwrite, what integer division by zero produces, how gdb...intro
- 5.83Intermediate quiz: ARMv8 assemblyArgument registers, instruction aliases, the frame record, integer division, condition flags, and stepping in gdb.core
- 5.84Advanced quiz: ARMv8 assemblyConvert a loop by hand, then account for exception levels, the program counter, multiply-accumulate, and integer division by zero.challenge
- 5.85Fill in the blank: ARMv8 assemblyFill in the missing mnemonics, suffixes, and symbols across stack frames, flag setting, branching, and gdb stepping.core
- 5.86Predict: ARMv8 assemblyPredict the register values and flags these AArch64 snippets leave behind.challenge
branching· 3
- 5.112Basic quiz: branchingCompares, the flags they leave, and the instructions that read them:
b.condwith signed and unsigned conditions,cbz, andcsel.intro - 5.113Fill in the blank: branchingFill in the instruction or condition each line needs:
csel,csetandcincpick a value with no branch,cbzguards a division, and an...core - 5.114Predict: branchingTrace what conditional selects, conditional increments, and zero tests leave in a register, with signed and unsigned conditions.challenge
- 5.112Basic quiz: branchingCompares, the flags they leave, and the instructions that read them:
loops· 4
- 5.115Basic quiz: loopsPre-test and post-test loops: when the test runs, where the step goes, how a branch condition sets the last pass, and which register keeps a...intro
- 5.116Intermediate quiz: loopsLoops inside loops, leaving a loop early, reading until the input runs out, counting passes, and the bugs a call inside a loop body can caus...core
- 5.117Fill in the blank: loopsFill in the branches and the subtract that open a loop, close it, and count it down.core
- 5.118Predict: loopsTrace counting loops, a post-test loop, a loop inside a loop, and an unsigned test, and say what a register holds when each one ends.challenge
bitwise· 3
- 5.130Basic quiz: bit manipulationSetting and clearing one bit with a mask, the AND of n with n - 1, branching on a single bit with
tbnz, moving a field down with a shift a...intro - 5.131Fill in the blank: bit manipulationFill in the missing mnemonic or number on each line so it sets, flips, tests, extracts or inserts the bits described.core
- 5.132Predict: bit manipulationFor each snippet, give the exact value left in the named register. The snippets clear, extract, insert, rotate, count and swap bits.challenge
- 5.130Basic quiz: bit manipulationSetting and clearing one bit with a mask, the AND of n with n - 1, branching on a single bit with
arrays· 5
- 5.87Basic quiz: arrays and structuresHow arrays and structures are laid out in memory, and how AArch64 code computes the address of a single element or field.intro
- 5.88Intermediate quiz: arrays and structuresAddress arithmetic for one- and two-dimensional arrays, scaled register offsets, and the constant offsets that reach struct fields.core
- 5.89Advanced quiz: arrays and structuresOffset arithmetic for multi-dimensional arrays and padded structures, scaled register addressing, and the constant that allocates an aligned...challenge
- 5.90Fill in the blank: arrays and structuresFill in the missing mnemonics, extend options, and offsets that reach array elements and struct fields.core
- 5.91Predict: arrays and structuresBlock sizes and byte offsets: how a C array declaration turns into the bytes to reserve and the offset a load uses.challenge
strings· 3
- 5.124Basic quiz: stringsHow text is stored as bytes: character codes, the zero byte that ends a string, the directives that store text, and the instructions that re...intro
- 5.125Fill in the blank: stringsFill in the missing piece of code that stores, walks, and changes a string one byte at a time.core
- 5.126Predict: stringsWork out the character codes, lengths, and numbers that byte loads, byte stores, and the
strlenfunction leave behind.challenge
memory and the stack· 6
- 5.92Basic quiz: memory and the stackCheck the basics: address size, which way the stack grows, the 16-byte alignment rule for
sp, the job of the frame pointer, and how a byte...intro - 5.93Intermediate quiz: memory and the stackAddressing modes, locals reached by frame-pointer offset, and the 16-byte alignment sp has to keep.core
- 5.94Advanced quiz: memory and the stackRegister-offset addressing with sign extension and shifts, plus the pre-indexed and post-indexed forms that save and restore the frame recor...challenge
- 5.95Fill in the blank: memory and the stackFill in the missing mnemonics, registers, directives, and symbols that complete these AArch64 instructions.core
- 5.96Predict: memory and the stackTrace the memory addresses and register values through these snippets. Write hex answers as 0x followed by the digits, and decimal answers a...challenge
- 5.133Basic quiz: debugging in the playgroundWhere a breakpoint stops a run, what reset keeps, the pause after 1,000,000 instructions, what a watch shows, the rows of the stack view, an...intro
- 5.92Basic quiz: memory and the stackCheck the basics: address size, which way the stack grows, the 16-byte alignment rule for
functions· 2
- 5.119Intermediate quiz: functionsRecursion and the register rules behind it: saving
x30andx19in every call, the frames a deep call leaves on the stack, and the frame...core - 5.120Predict: functionsTrace recursive calls, saved registers, and frame records, and say what a function returns or where it stores a value.challenge
- 5.119Intermediate quiz: functionsRecursion and the register rules behind it: saving
subroutines· 5
- 5.97Basic quiz: subroutinesOpen and closed subroutines, the argument and result registers, and how
blandretcarry the return address.intro - 5.98Intermediate quiz: subroutinesFollow a call through the AArch64 procedure call convention: the link register, the frame record chain, saved registers, argument passing, a...core
- 5.99Advanced quiz: subroutinesThe procedure call standard: when a leaf routine (one that calls nothing) can skip its frame, what 16-byte alignment actually demands, who p...challenge
- 5.100Fill in the blank: subroutinesFill in the missing mnemonics and registers that let an AArch64 subroutine be called, build a frame, return a result, and hand back the regi...core
- 5.101Predict: subroutinesTrace the register states and stack allocations a subroutine call sets up.challenge
- 5.97Basic quiz: subroutinesOpen and closed subroutines, the argument and result registers, and how
input and output· 3
- 5.121Basic quiz: input and outputHow
printf,scanfand system calls move text in and out of a program: the addressesscanfneeds, format specifiers, file descriptors,...intro - 5.122Fill in the blank: input and outputFill in the missing token in calls to
scanfandprintf, and to thereadandwritesystem calls.core - 5.123Predict: input and outputWhat
printf,scanf,readandwritehand back inw0orx0, and what a specifier that does not match its slot leaves behind.challenge
- 5.121Basic quiz: input and outputHow
command-line arguments· 2
- 5.127Basic quiz: command-line argumentsHow the words typed after a program's name reach
main:argc, theargvarray of string addresses, andatoi, which turns an argument i...intro - 5.128Predict: command-line argumentsWork out what
argc, theargventries,strlenandatoigive for the command line each question names.challenge
- 5.127Basic quiz: command-line argumentsHow the words typed after a program's name reach
external data· 5
- 5.102Basic quiz: external dataWhere a program's data lives in
.data,.bss, and.text, how character constants are written, and howargcandargvreachmain.intro - 5.103Intermediate quiz: external dataWhere a program's data lives: the
.text,.data, and.bsssections, the string directives, and howadrpforms an address.core - 5.104Advanced quiz: external dataVariable scope, building an address relative to the program counter with
adrpandadd, section permissions, and indexing an array of poi...challenge - 5.105Fill in the blank: external dataFill in the missing pieces of data declared outside a function: a
.bssreservation,.datavalues and string literals, a label shared wit...core - 5.106Predict: external dataHow bytes land in
.data: the size of each directive, what a string literal costs, how a table of addresses is indexed, and what happens to...core
- 5.102Basic quiz: external dataWhere a program's data lives in
floating point· 7
- 5.107Basic quiz: floating pointHow the single and double precision views of one register differ, which directives place floating-point values in memory, what operands the...intro
- 5.108Intermediate quiz: floating pointSingle and double precision registers, which ones a subroutine has to preserve, conversions between the two formats, and the rules for arith...core
- 5.109Advanced quiz: floating pointThe callee-saved
dregisters, thefmovimmediate range, conversions between integers and floats, and the fused multiply-add family.challenge - 5.110Fill in the blank: floating pointFill in the missing directive, mnemonics, and gdb command used to declare floating-point values in memory, convert an integer to single prec...core
- 5.111Predict: floating pointTrace single and double precision arithmetic by hand: add, fused multiply-add, multiply-negate, and the two instructions that change only th...core
- 5.134Basic quiz: vectorsThe lanes and arrangements of a
vregister, the scalar names for its low bits, the lane-by-laneadd, the saturatinguqadd,dup, copy...intro - 5.135Predict: vectorsFor each snippet, give the exact value left in the named general register. Every snippet works on lanes, then copies one lane or a total out...challenge
progress: