Skip to content
Tutorials Center
My learning

Topics

Lesson 7 of 37 ยท Language Basics

Integers and Floating-Point Numbers

Master Zig numeric types: i8 to i128, u8 to u64, usize, arbitrary bit widths, f32 and f64, overflow operators +% and +|, @intCast, @as and @floatFromInt.

Numbers in Zig are explicit. Every integer has a sign and an exact bit width in its name, there is no vague int or long, and the compiler checks conversions. This costs a few keystrokes and removes the classic C questions: "How big is long here?", "Is char signed?", and "Did that implicit conversion lose data?"

Integer types

Signed integers start with i, unsigned with u, followed by the number of bits:

Type Range
u8 0 to 255
i8 -128 to 127
u16, i16 0 to 65 535, and -32 768 to 32 767
u32, i32 0 to about 4.29 billion, and about plus or minus 2.1 billion
u64, i64 up to about 1.8 x 10^19, and about plus or minus 9.2 x 10^18
u128, i128 enormous
usize, isize pointer-sized (64 bits on a 64-bit machine)

usize is the type of array lengths and indexes. Zig allows any bit width from 1 to 65 535: u3 holds 0 to 7, i5 holds -16 to 15, u1 is a single bit. Odd widths are handy for protocols, flags and packed data, and they work with all the usual operators.

You can read the limits from the type itself:

ZIG
const std = @import("std");

pub fn main() void {
    std.debug.print("u8 max = {d}\n", .{std.math.maxInt(u8)});
    std.debug.print("i8 min = {d}\n", .{std.math.minInt(i8)});
    std.debug.print("u3 max = {d}\n", .{std.math.maxInt(u3)});
    std.debug.print("size of u64 = {d} bytes\n", .{@sizeOf(u64)});
}
TEXT
u8 max = 255
i8 min = -128
u3 max = 7
size of u64 = 8 bytes

Floating-point types

f32 (single precision), f64 (double precision, the usual default), f16, f80 and f128 exist too. Float literals have the type comptime_float until used. Special values are available through std.math: std.math.inf(f64), std.math.nan(f64), and std.math.isNan(x) tests for NaN.

ZIG
const price: f64 = 19.99;
const tax = price * 0.2;       // f64
const half: f32 = 0.5;

Float formatting uses or {d:.2}; the plain {} prints in scientific notation for floats in recent versions, so prefer for human-readable numbers.

Division and remainder

/ on integers is only allowed when the result is clear. For signed integers use the explicit builtins:

ZIG
const a: i32 = 7;
const b: i32 = 2;
_ = a / b;           // allowed when both values are known positive at compile time
_ = @divTrunc(-7, 2); // -3: rounds toward zero
_ = @divFloor(-7, 2); // -4: rounds toward negative infinity
_ = @mod(-7, 3);      // 2: result has the sign of the divisor
_ = @rem(-7, 3);      // -1: result has the sign of the dividend

For runtime signed values, plain / and % can be ambiguous when negative, so the compiler asks you to choose with @divTrunc, @divFloor, @mod or @rem. Unsigned integers use / and % directly. Dividing by zero is detected in safe build modes.

Overflow: three behaviors

What does 255 + 1 mean for a u8? Zig gives you three explicit answers through different operators:

Operator Behavior Example with u8 250 + 10
+ Overflow is a bug: panics in Debug/ReleaseSafe, undefined behavior in release-fast modes panic
+% Wraps around (modular arithmetic) 4
`+ ` Saturates at the limit

The same pattern holds for -%, -|, *%, *| and the compound forms +%= and +|=.

ZIG
const std = @import("std");

pub fn main() void {
    const x: u8 = 250;
    std.debug.print("wrapping:   {d}\n", .{x +% 10});
    std.debug.print("saturating: {d}\n", .{x +| 10});

    const result = @addWithOverflow(x, 10);
    std.debug.print("value {d}, overflowed {d}\n", .{ result[0], result[1] });
}
TEXT
wrapping:   4
saturating: 255
value 4, overflowed 1

@addWithOverflow returns a tuple: the wrapped result and a one-bit overflow flag. Hash functions and checksums want wrapping; audio and color math often want saturating; everything else wants the checked +.

Converting between number types

Zig never converts a number to a narrower type silently. Widening that cannot lose data is allowed implicitly (u8 to u32, i16 to i32); everything else needs a builtin:

ZIG
const small: u8 = 200;
const wide: u32 = small;                 // fine: u8 always fits in u32

const big: u32 = 300;
const narrow: u8 = @intCast(big);        // checked: panics in safe modes (300 > 255)

const f: f64 = @floatFromInt(wide);      // integer to float
const n: i32 = @intFromFloat(3.9);       // float to integer, truncates: 3
const g: f32 = @floatCast(f);            // f64 to f32
const t = @as(u16, 7);                   // give a literal a type
const w: u8 = @truncate(big);            // keep the low bits: 300 -> 44

@intCast, @floatCast and similar builtins take their target type from the result location, so you must write the destination type on the declaration (const narrow: u8 = ...). If the type cannot be inferred, wrap with @as(u8, @intCast(big)).

@truncate discards high bits without a check; @intCast asserts the value fits. Choose based on whether losing bits is a bug (intCast) or the intent (truncate).

Mixing signed and unsigned

An i32 and a u32 cannot be added directly: the compiler stops you. This prevents the C trap where -1 < 1u is false. Convert explicitly:

ZIG
const delta: i32 = -3;
const index: usize = 10;
const moved: usize = @intCast(@as(isize, @intCast(index)) + delta);
// moved == 7

It looks long, but each cast marks a place where a check happens.

Stand-ins you can run

The three overflow behaviors have direct Rust counterparts, so you can see the values yourself.

Rust Stand-in (Rust): checked, wrapping, saturating and overflow flag

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

C shows why Zig's explicitness matters: its signed/unsigned comparison surprises.

C Stand-in (C): the trap Zig refuses to compile

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What is the largest value a u3 can hold?

    A u3 has 3 bits, so it holds 0 through 2^3 - 1, which is 7.
  2. 2. What is @as(u8, 250) +% 10?

    The +% operator wraps around modulo 256, so 260 becomes 4.
  3. 3. Which operator clamps the result at the type's maximum?

    +| is saturating addition.
  4. 4. How do you convert a u32 named n to a u8 and have Zig check that it fits?

    @intCast asserts the value fits (panics in safe modes); @truncate keeps low bits without checking.
  5. 5. Which type is used for array lengths and indexes?

    usize is pointer-sized and is the type of lengths, indexes and sizes.

Summary

  • Integer types state sign and width (u8, i32, u3); usize is for sizes and indexes; floats are f32 and f64.
  • + checks overflow in safe modes, +% wraps, +| saturates, and @addWithOverflow reports it.
  • Narrowing conversions are explicit: @intCast (checked), @truncate, @floatFromInt, @intFromFloat.
  • Signed division uses @divTrunc, @divFloor, @mod and @rem.
  • Signed and unsigned values never mix implicitly.

Next: Booleans and Operators