TExcelTAD
Home › WebAssembly › WebAssembly Exercises

WebAssembly Exercises

Time to practise! Each exercise has a starter playground that already compiles and runs: it prints a placeholder result so you can see the expected format. Replace the TODO parts, press ▶ Run, and compare your output with the "Expected" line. If you get stuck, open the solution, but try for a few minutes first.

# Exercise Topics
1 Temperature conversion f64 arithmetic, conversions
2 Maximum of three comparisons, select
3 Digit sum loops, div_u/rem_u
4 Prime test loops, early return
5 Vowel counter memory, data segments, bytes
6 Reverse a string in place two pointers, loads/stores
7 Operation table tables, call_indirect
8 LEB128 decoder the binary format, JavaScript

1. Temperature conversion

Write $c_to_f that converts an i32 Celsius value to an f64 Fahrenheit value with F = C × 9 / 5 + 32.

Expected: -40, 32, 98.6, 212 (one per line).

wat · try it yourself
(module
  (import "console" "log" (func $log (param f64)))
  (func $c_to_f (param $c i32) (result f64)
    ;; TODO: convert $c to f64 and apply the formula
    (f64.const 0))
  (func (export "main")
    (call $log (call $c_to_f (i32.const -40)))
    (call $log (call $c_to_f (i32.const 0)))
    (call $log (call $c_to_f (i32.const 37)))
    (call $log (call $c_to_f (i32.const 100)))))
0
0
0
0
Show solution
wat
(func $c_to_f (param $c i32) (result f64)
  (f64.add
    (f64.div (f64.mul (f64.convert_i32_s (local.get $c)) (f64.const 9)) (f64.const 5))
    (f64.const 32)))

f64.convert_i32_s is needed because Wasm never mixes types implicitly. The _s matters for -40.

2. Maximum of three

Write $max3 returning the largest of three signed i32s, without if (use select).

Expected: 9, -1, 7.

wat · try it yourself
(module
  (import "console" "log" (func $log (param i32)))
  (func $max3 (param $a i32) (param $b i32) (param $c i32) (result i32)
    ;; TODO
    (local.get $a))
  (func (export "main")
    (call $log (call $max3 (i32.const 4) (i32.const 9) (i32.const 2)))
    (call $log (call $max3 (i32.const -5) (i32.const -1) (i32.const -3)))
    (call $log (call $max3 (i32.const 7) (i32.const 7) (i32.const 1)))))
4
-5
7
Show solution
wat
(func $max2 (param $a i32) (param $b i32) (result i32)
  (select (local.get $a) (local.get $b) (i32.gt_s (local.get $a) (local.get $b))))
(func $max3 (param $a i32) (param $b i32) (param $c i32) (result i32)
  (call $max2 (call $max2 (local.get $a) (local.get $b)) (local.get $c)))

Use gt_s, not gt_u: with an unsigned comparison -1 would be the largest value.

3. Digit sum

Write $digit_sum that adds up the decimal digits of a non-negative number (2026 → 2 + 0 + 2 + 6 = 10).

Expected: 10, 0, 45.

wat · try it yourself
(module
  (import "console" "log" (func $log (param i32)))
  (func $digit_sum (param $n i32) (result i32)
    (local $sum i32)
    ;; TODO: loop while n != 0: sum += n % 10; n /= 10
    (local.get $sum))
  (func (export "main")
    (call $log (call $digit_sum (i32.const 2026)))
    (call $log (call $digit_sum (i32.const 0)))
    (call $log (call $digit_sum (i32.const 123456789)))))
0
0
0
Show solution
wat
(func $digit_sum (param $n i32) (result i32)
  (local $sum i32)
  (block $done
    (loop $next
      (br_if $done (i32.eqz (local.get $n)))
      (local.set $sum (i32.add (local.get $sum) (i32.rem_u (local.get $n) (i32.const 10))))
      (local.set $n (i32.div_u (local.get $n) (i32.const 10)))
      (br $next)))
  (local.get $sum))

The test sits at the top (a while loop), so 0 correctly gives 0.

4. Prime test

Write $is_prime returning 1 if n is prime and 0 otherwise. Try divisors d = 2, 3, … while d * d <= n.

Expected: 0 0 1 1 0 1 for 0, 1, 2, 97, 91, 7919.

wat · try it yourself
(module
  (import "console" "log" (func $log (param i32)))
  (func $is_prime (param $n i32) (result i32)
    ;; TODO
    (i32.const 0))
  (func (export "main")
    (call $log (call $is_prime (i32.const 0)))
    (call $log (call $is_prime (i32.const 1)))
    (call $log (call $is_prime (i32.const 2)))
    (call $log (call $is_prime (i32.const 97)))
    (call $log (call $is_prime (i32.const 91)))
    (call $log (call $is_prime (i32.const 7919)))))
0
0
0
0
0
0
Show solution
wat
(func $is_prime (param $n i32) (result i32)
  (local $d i32)
  (if (i32.lt_u (local.get $n) (i32.const 2)) (then (return (i32.const 0))))
  (local.set $d (i32.const 2))
  (block $done
    (loop $next
      (br_if $done (i32.gt_u (i32.mul (local.get $d) (local.get $d)) (local.get $n)))
      (if (i32.eqz (i32.rem_u (local.get $n) (local.get $d)))
        (then (return (i32.const 0))))
      (local.set $d (i32.add (local.get $d) (i32.const 1)))
      (br $next)))
  (i32.const 1))

91 = 7 × 13, a classic number that looks prime but isn't.

5. Vowel counter

Count the vowels (a e i o u, either case) in the string stored at address 0.

Expected: 5 for "WebAssembly is fun" (e, A, e, i, u), then 5 for "AEIOU".

wat · try it yourself
(module
  (import "console" "log" (func $log (param i32)))
  (memory 1)
  (data (i32.const 0) "WebAssembly is fun")
  (data (i32.const 32) "AEIOU")
  (func $count_vowels (param $p i32) (param $len i32) (result i32)
    (local $count i32)
    ;; TODO: for each byte, lowercase it (c | 0x20) and compare with 'a' 'e' 'i' 'o' 'u'
    (local.get $count))
  (func (export "main")
    (call $log (call $count_vowels (i32.const 0) (i32.const 18)))
    (call $log (call $count_vowels (i32.const 32) (i32.const 5)))))
0
0
Show solution
wat
(func $is_vowel (param $c i32) (result i32)
  (local.set $c (i32.or (local.get $c) (i32.const 0x20)))     ;; ASCII lowercase
  (i32.or
    (i32.or (i32.eq (local.get $c) (i32.const 97)) (i32.eq (local.get $c) (i32.const 101)))
    (i32.or (i32.or (i32.eq (local.get $c) (i32.const 105)) (i32.eq (local.get $c) (i32.const 111)))
            (i32.eq (local.get $c) (i32.const 117)))))
(func $count_vowels (param $p i32) (param $len i32) (result i32)
  (local $count i32)
  (block $done
    (loop $next
      (br_if $done (i32.eqz (local.get $len)))
      (local.set $count (i32.add (local.get $count) (call $is_vowel (i32.load8_u (local.get $p)))))
      (local.set $p (i32.add (local.get $p) (i32.const 1)))
      (local.set $len (i32.sub (local.get $len) (i32.const 1)))
      (br $next)))
  (local.get $count))

Setting bit 5 (| 0x20) lowercases ASCII letters. Because $is_vowel returns exactly 0 or 1, it can be added straight to the count.

6. Reverse a string in place

Reverse the bytes of the string at address 0, using two pointers that move toward each other.

Expected: !ylbmessAbeW (then the original string reversed back: WebAssembly!).

wat · try it yourself
(module
  (import "console" "str" (func $print (param i32 i32)))
  (memory (export "memory") 1)
  (data (i32.const 0) "WebAssembly!")
  (func $reverse (param $p i32) (param $len i32)
    ;; TODO: swap bytes at $left and $right until they meet
    )
  (func (export "main")
    (call $reverse (i32.const 0) (i32.const 12))
    (call $print (i32.const 0) (i32.const 12))
    (call $reverse (i32.const 0) (i32.const 12))
    (call $print (i32.const 0) (i32.const 12))))
WebAssembly!
WebAssembly!
Show solution
wat
(func $reverse (param $p i32) (param $len i32)
  (local $right i32) (local $tmp i32)
  (local.set $right (i32.sub (i32.add (local.get $p) (local.get $len)) (i32.const 1)))
  (block $done
    (loop $next
      (br_if $done (i32.ge_u (local.get $p) (local.get $right)))
      (local.set $tmp (i32.load8_u (local.get $p)))
      (i32.store8 (local.get $p) (i32.load8_u (local.get $right)))
      (i32.store8 (local.get $right) (local.get $tmp))
      (local.set $p (i32.add (local.get $p) (i32.const 1)))
      (local.set $right (i32.sub (local.get $right) (i32.const 1)))
      (br $next))))

This reverses bytes, which is correct for ASCII. For UTF-8 text with multi-byte characters you'd have to reverse whole characters.

7. Operation table

Fill a table with three functions $inc, $double and $square (all (i32) -> i32) and write $apply_all that applies the operations at table indices given in the $ops byte list, in order, to a starting value.

Expected: starting from 3 with ops 0 1 2 0 (inc, double, square, inc): 4, 8, 64, 65.

wat · try it yourself
(module
  (import "console" "log" (func $log (param i32)))
  (memory 1)
  (type $unop (func (param i32) (result i32)))
  (func $inc (type $unop) (i32.add (local.get 0) (i32.const 1)))
  (func $double (type $unop) (i32.mul (local.get 0) (i32.const 2)))
  (func $square (type $unop) (i32.mul (local.get 0) (local.get 0)))
  ;; TODO: declare a table and an elem segment with $inc $double $square
  (data (i32.const 0) "\00\01\02\00")     ;; the ops list
  (func $apply_all (param $value i32) (param $ops i32) (param $count i32)
    ;; TODO: for each op byte, value = call_indirect(op)(value); log value
    (call $log (local.get $value)))
  (func (export "main")
    (call $apply_all (i32.const 3) (i32.const 0) (i32.const 4))))
3
Show solution
wat
(table 3 funcref)
(elem (i32.const 0) $inc $double $square)

(func $apply_all (param $value i32) (param $ops i32) (param $count i32)
  (block $done
    (loop $next
      (br_if $done (i32.eqz (local.get $count)))
      (local.set $value
        (call_indirect (type $unop) (local.get $value) (i32.load8_u (local.get $ops))))
      (call $log (local.get $value))
      (local.set $ops (i32.add (local.get $ops) (i32.const 1)))
      (local.set $count (i32.sub (local.get $count) (i32.const 1)))
      (br $next))))

An op byte of 3 or more would trap with "table index is out of bounds": the table check keeps it safe.

8. LEB128 decoder

Write decodeLeb(bytes, pos) that decodes an unsigned LEB128 number and returns [value, bytesUsed].

Expected: [ 624485, 3 ], [ 127, 1 ], [ 300, 2 ].

js · try it yourself
function decodeLeb(bytes, pos) {
  // TODO: accumulate 7 bits per byte, stop at the first byte without 0x80
  return [0, 0];
}

console.log(decodeLeb([0xe5, 0x8e, 0x26], 0));
console.log(decodeLeb([0x7f], 0));
console.log(decodeLeb([0x00, 0xac, 0x02], 1));
[ 0, 0 ]
[ 0, 0 ]
[ 0, 0 ]
Show solution
js
function decodeLeb(bytes, pos) {
  let result = 0, shift = 0, used = 0, byte;
  do {
    byte = bytes[pos + used++];
    result |= (byte & 0x7f) << shift;
    shift += 7;
  } while (byte & 0x80);
  return [result >>> 0, used];
}

>>> 0 turns the result into an unsigned 32-bit number, so values with the top bit set don't come out negative.

Test yourself

In exercise 2, why must $max2 use i32.gt_s instead of i32.gt_u?

  1. gt_u doesn't exist
  2. With unsigned comparison, negative numbers look huge, so -1 would win
  3. select requires signed conditions
  4. It doesn't matter

In exercise 5, why can $is_vowel's result be added directly to the count?

  1. Because it returns 0 or 1
  2. Because Wasm converts booleans automatically
  3. Because i32.or returns the count
  4. It can't