Getting startedSlide 9 of 86
9UInt8Getting started

Sized numbers

When a program keeps many small numbers, each can take only the bits it needs:

  • UInt1 … UInt64 are unsigned integers of that many bits, so a UInt4 holds 0 to 15. Int1 … Int63 are signed, so an Int4 holds −8 to 7. Int64 is another name for Int.
  • Float32 is a 32-bit float, about seven digits. Float64 is another name for Float.
  • A sized integer wraps at its own width, the way Int wraps at 64: a UInt4 at 15 plus one is 0. - on an unsigned type is a compile error.
  • A literal takes the type it lands in, and has to fit it: UInt4 x = 16 is a compile error.
  • No number changes type on its own: a UInt8 becomes an Int only through Int(x), a Float32 a Float only through Float(x), and UInt4 + UInt8 is a compile error until one side is converted. Two integers of any sizes still compare by value.
  • UInt4(x) keeps the low bits and never fails, and UInt4.checked(x) answers Error(x) where x does not fit.
  • A sized index is its own bounds proof: a UInt4 indexes any vector of 16 or more with no guard.
  • A vector of them is packed, each value taking only its own bits: a million UInt4s take half a megabyte.
type Pixel {
	r: UInt8
	g: UInt8
	b: UInt8
}

proc main(): void {
	UInt4 level = 15
	echo level + 1            // 0 — a UInt4 wraps at 16
	Int wide = Int(level)     // widened, and said so
	echo wide + 1             // 16
	echo UInt8(300)           // 44 — the low 8 bits
	echo UInt8.checked(300)   // Error(300)
	echo Pixel(255, 128, 0)   // {255, 128, 0}
	Float32 third = 0.1
	echo third                // 0.1

	Str[16] names = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p"]
	echo names[level]         // p — no guard: a UInt4 is at most 15

	UInt4[dyn] steps = [3, 1, 4, 1, 5, 9, 2, 6]
	echo bytes(steps)         // 8 — packed: all eight in one 64-bit word
}