typestar

Conversions in WebAssembly

destination.op_source, signedness included — nothing is implicit.

(module
  ;; Conversions are all spelled out: destination.op_source, with
  ;; signedness where it matters. Nothing converts implicitly.
  (func (export "ratio") (param $part i32) (param $whole i32)
        (result f64)
    (f64.div
      (f64.convert_i32_s (local.get $part))
      (f64.convert_i32_s (local.get $whole))))

  ;; trunc drops the fraction and traps if it cannot fit.
  (func (export "whole_meters") (param $km f64) (result i32)
    (i32.trunc_f64_s (f64.mul (local.get $km) (f64.const 1000))))

  (func (export "shrink") (param $precise f64) (result f32)
    (f32.demote_f64 (local.get $precise))))

How it works

  1. f64.convert_i32_s reads an integer into float land.
  2. i32.trunc_f64_s drops the fraction and traps on overflow.
  3. f32.demote_f64 narrows a float; promote would widen it.

Keywords and builtins used here

The run, in numbers

Lines
15
Characters to type
570
Tokens
103
Three-star pace
60 tpm

At the three-star pace of 60 tokens a minute, this run takes about 103 seconds.

Type this snippet

Step 2 of 3 in Wider types, step 24 of 28 in Language basics.

← Previous Next →

Conversions in other languages