Zig Integers
Integers are whole numbers: 0, 42, -7. In Python you just write a number and never think about its size. In Zig you choose a type for each one, and the type says how many bits it has and whether it can be negative. That sounds like extra work, but it’s a small habit, and the compiler uses it to catch values that can’t fit before your program even runs.
Signed and unsigned
Section titled “Signed and unsigned”Every integer type is a letter plus a number:
umeans unsigned: zero or more, never negative.imeans signed: can be negative.- The number is the size in bits.
So u8 is an unsigned 8-bit number and i32 is a signed 32-bit number. The standard library can tell you the smallest and largest value of any integer type:
const std = @import("std");
pub fn main() void { std.debug.print("u8: {d} to {d}\n", .{ std.math.minInt(u8), std.math.maxInt(u8) }); std.debug.print("i8: {d} to {d}\n", .{ std.math.minInt(i8), std.math.maxInt(i8) }); std.debug.print("u32: {d} to {d}\n", .{ std.math.minInt(u32), std.math.maxInt(u32) }); std.debug.print("i32: {d} to {d}\n", .{ std.math.minInt(i32), std.math.maxInt(i32) }); std.debug.print("u64: {d} to {d}\n", .{ std.math.minInt(u64), std.math.maxInt(u64) });}Output:
u8: 0 to 255i8: -128 to 127u32: 0 to 4294967295i32: -2147483648 to 2147483647u64: 0 to 18446744073709551615A signed type uses one of its bits for the sign, so i8 reaches only half as high as u8. The common sizes are 8, 16, 32, 64 and 128 bits. Signed numbers are stored in two’s complement, the same way C, Rust and almost every CPU do it.
Giving a value a type
Section titled “Giving a value a type”You pick the type with an annotation. If the value doesn’t fit, the build fails:
const std = @import("std");
pub fn main() void { const temperature: u8 = -5; std.debug.print("{d}\n", .{temperature});}main.zig:4:29: error: type 'u8' cannot represent integer value '-5' const temperature: u8 = -5; ^~The fix is a signed type, like const temperature: i8 = -5;. Errors like this are why Zig asks you to pick a type: the mistake shows up on your screen now, not as a strange number in production.
Which type should you pick?
Section titled “Which type should you pick?”There’s no single “default int” in Zig like int in C or Java. A few habits cover most cases:
| You’re storing | Good choice | Why |
|---|---|---|
| A byte, or an ASCII character | u8 |
Exactly one byte |
| A count, a length, an index into an array | usize |
It’s what .len and indexing use |
| A general number that can be negative | i32 or i64 |
Plenty of room both ways |
| A general number that is never negative | u32 or u64 |
Same, but unsigned |
| Something with a known small range | Whatever fits, like u3 or u16 |
Saves space, documents the range |
If you’re not sure, i64 is hard to overflow and costs very little on a 64-bit computer. Signed vs unsigned matters more than the size: choosing unsigned says “this is never negative”, and Zig will hold you to it.
Any width you like
Section titled “Any width you like”Zig isn’t limited to 8, 16, 32 and 64. You can write u or i followed by any number up to 65535. A u3 holds 0 to 7, an i7 holds -64 to 63:
const std = @import("std");
pub fn main() void { const weekday: u3 = 6; // 0 = Monday ... 6 = Sunday const offset: i7 = -40; std.debug.print("weekday {d}, offset {d}\n", .{ weekday, offset }); std.debug.print("u3 goes up to {d}, i7 goes from {d} to {d}\n", .{ std.math.maxInt(u3), std.math.minInt(i7), std.math.maxInt(i7), });}Output:
weekday 6, offset -40u3 goes up to 7, i7 goes from -64 to 63This is rare in other languages, and it’s genuinely useful. A u3 documents “only 0 to 7 are valid here”, and the compiler checks it: const weekday: u3 = 8; fails with type 'u3' cannot represent integer value '8'. Odd widths really shine in packed structs, where you lay out bits exactly, for example in file formats and hardware registers.
usize: the type for lengths and indexes
Section titled “usize: the type for lengths and indexes”usize is an unsigned integer as wide as a memory address: 64 bits on a 64-bit computer, 32 bits on a 32-bit one. Zig uses it for anything that counts memory, so the length of an array and the index you use to read from it are both usize:
const std = @import("std");
pub fn main() void { const scores = [_]u32{ 90, 75, 88 }; const count = scores.len; const last_index: usize = count - 1; std.debug.print("{d} scores, the last is {d}\n", .{ count, scores[last_index] }); std.debug.print("count is a {}\n", .{@TypeOf(count)});}Output:
3 scores, the last is 88count is a usize[_]u32{ 90, 75, 88 } is an array of three u32s (arrays get their own lesson, Zig Arrays). It’s in C as size_t. There’s also isize, the signed version, which you’ll rarely need.
The thing that trips people up is using an i32 as an index:
const std = @import("std");
pub fn main() void { const scores = [_]u32{ 90, 75, 88 }; var i: i32 = 1; _ = &i; std.debug.print("{d}\n", .{scores[i]});}main.zig:7:39: error: expected type 'usize', found 'i32' std.debug.print("{d}\n", .{scores[i]}); ^main.zig:7:39: note: unsigned 64-bit int cannot represent all possible signed 32-bit valuesAn i32 could be negative, and a negative index makes no sense, so Zig won’t silently convert it. Declare index variables as usize from the start. (_ = &i; is the demo trick from Zig Variables that keeps i a real runtime var.)
Writing number literals
Section titled “Writing number literals”You can write integers in four bases, and add _ anywhere between digits to make long numbers readable:
const std = @import("std");
pub fn main() void { const decimal = 1_000_000; const hex = 0xFF; const octal = 0o755; const binary = 0b1111_0000; const letter = 'A'; std.debug.print("{d} {d} {d} {d} {d}\n", .{ decimal, hex, octal, binary, letter });}Output:
1000000 255 493 240 650x is hexadecimal, 0o is octal (note the letter o, unlike C’s leading 0), and 0b is binary. A character in single quotes is an integer too: 'A' is 65. The underscores don’t change the value at all. The reference has the full list under integer literals.
comptime_int: numbers with no size
Section titled “comptime_int: numbers with no size”A number you type into your code, like 1_000_000, starts out as a comptime_int. That type has no size limit, because the number only exists inside the compiler so far:
const std = @import("std");
pub fn main() void { const huge = 1 << 100; // 2 to the power 100 const small: u8 = 200; std.debug.print("{d}\n", .{huge}); std.debug.print("{} and {}\n", .{ @TypeOf(huge), @TypeOf(small) });}Output:
1267650600228229401496703205376comptime_int and u81 << 100 is far too big for even a u64, but that’s fine, because the compiler does the math and nothing is stored at runtime. When you put a comptime_int into a typed place (const small: u8 = 200;), it becomes that type, and the compiler checks it fits.
This is also why var x = 5; is an error: a var lives in memory while the program runs, and the compiler can’t store a number with no size. Write var x: i32 = 5;.
Mixing integer types
Section titled “Mixing integer types”Zig converts between integer types on its own only when nothing can go wrong. A u8 fits inside a u16, so adding them is fine, and the result is a u16:
const std = @import("std");
pub fn main() void { const apples: u8 = 200; const boxes: u16 = 1000; const total = apples + boxes; std.debug.print("{d} is a {}\n", .{ total, @TypeOf(total) });}Output:
1200 is a u16But an i32 and a u32 can’t always fit in each other (one has negatives, the other has bigger positives), so a + b with those two types is a compile error: incompatible types: 'i32' and 'u32'. You convert one of them yourself, which is the topic of Zig Type Casting.
Dividing integers
Section titled “Dividing integers”Integer division drops the remainder, and % gives you the remainder:
const std = @import("std");
pub fn main() void { const cookies: u32 = 17; const kids: u32 = 5; std.debug.print("each kid gets {d}, {d} left over\n", .{ cookies / kids, cookies % kids });}Output:
each kid gets 3, 2 left overWith signed numbers there’s a catch. What’s -7 / 2? C says -3 (round toward zero), Python says -4 (round down). Both are reasonable, so Zig doesn’t pick one for you. Plain / on signed values that aren’t known at compile time is an error that tells you to choose:
const std = @import("std");
pub fn main() void { var a: i32 = -7; _ = &a; std.debug.print("{d}\n", .{a / 2});}main.zig:6:34: error: division with 'i32' and 'comptime_int': signed integers must use @divTrunc, @divFloor, @divCeil, or @divExact std.debug.print("{d}\n", .{a / 2}); ~~^~~So you say what you mean:
const std = @import("std");
pub fn main() void { var a: i32 = -7; _ = &a; std.debug.print("@divTrunc: {d}\n", .{@divTrunc(a, 2)}); std.debug.print("@divFloor: {d}\n", .{@divFloor(a, 2)}); std.debug.print("@divCeil: {d}\n", .{@divCeil(a, 2)}); std.debug.print("@rem: {d}\n", .{@rem(a, 2)}); std.debug.print("@mod: {d}\n", .{@mod(a, 2)});}Output:
@divTrunc: -3@divFloor: -4@divCeil: -3@rem: -1@mod: 1@divTrunc rounds toward zero, like C. @divFloor rounds down, like Python’s //. @divCeil (new in Zig 0.17) rounds up. Here -3.5 rounded up is -3, the same as toward zero, but on positive numbers it’s the one you want for questions like “how many pages do 7 items need, 2 per page?”: @divCeil(7, 2) is 4. For remainders, @rem matches C’s % and @mod matches Python’s %. @divExact is for when you know there’s no remainder, and it’s a bug if there is one.
Practice
Section titled “Practice”1. Pick types that fit
Section titled “1. Pick types that fit”Give each constant the smallest unsigned type that holds it, and print them: 200, 1000, 5 (a value that can only ever be 0 to 7). Expected output: 200 1000 5.
Hint: u8 reaches 255, u16 reaches 65535, and you can make a type exactly 3 bits wide.
Show solution
const std = @import("std");
pub fn main() void { const a: u8 = 200; const b: u16 = 1000; const c: u3 = 5; std.debug.print("{d} {d} {d}\n", .{ a, b, c });}Output:
200 1000 51000 is too big for a u8 (the compiler would tell you), so it needs a u16. A u3 holds 0 to 7, which matches the stated range exactly.
2. Minutes and seconds
Section titled “2. Minutes and seconds”You have const total_seconds: u32 = 754;. Print it as minutes and seconds: 12 min 34 s.
Hint: use / for the minutes and % for what’s left. Unsigned numbers can use the plain operators.
Show solution
const std = @import("std");
pub fn main() void { const total_seconds: u32 = 754; const minutes = total_seconds / 60; const seconds = total_seconds % 60; std.debug.print("{d} min {d} s\n", .{ minutes, seconds });}Output:
12 min 34 s754 divided by 60 is 12 with 34 left over. Both results are u32, the type of total_seconds.
3. Round down, not toward zero
Section titled “3. Round down, not toward zero”A thermometer reads var reading: i32 = -9;. Split it into steps of 4 degrees, rounding down: print step -3. Use _ = &reading; to keep it a runtime value.
Hint: -9 / 4 is -2.25. Rounding toward zero gives -2, rounding down gives -3.
Show solution
const std = @import("std");
pub fn main() void { var reading: i32 = -9; _ = &reading; std.debug.print("step {d}\n", .{@divFloor(reading, 4)});}Output:
step -3@divFloor always rounds toward negative infinity. @divTrunc(reading, 4) would print step -2.
uNis unsigned andiNis signed, where N is the number of bits.std.math.maxInt(T)andminInt(T)give the limits.- Any width up to 65535 works, like
u3ori7, and the compiler checks values fit. - Use
usizefor lengths, counts and indexes. Indexing with ani32is a compile error. - Literals can be decimal,
0xhex,0ooctal or0bbinary, with_separators. - A literal is a
comptime_intwith no size limit until it’s put into a typed place. - Signed division needs
@divTrunc,@divFlooror@divCeil(and@remor@mod), so you choose how to round.
Next up: Zig Floats, numbers with a decimal point and the surprises that come with them.
Quick check
Section titled “Quick check”Quick check
Read more
Section titled “Read more”- Zig language reference: Integers: literals, runtime integer values and arbitrary bit widths.
- Zig language reference: Primitive Types: every integer type and its C equivalent.
- Zig language reference: @divFloor: the division builtins, with
@divCeil,@divTrunc,@divExact,@remand@modnext to it. - Zig language reference: Type Coercion, integer widening: when Zig converts between integer types on its own.