@intCast

@intCast

@intCast(int: anytype) anytype

Converts an integer to another integer while keeping the same numerical value. The return type is the inferred result type. Attempting to convert a number which is out of range of the destination type results in safety-protected Undefined Behavior.

test_intCast_builtin.zig

test "integer cast panic" {
    var a: u16 = 0xabcd; // runtime-known
    _ = &a;
    const b: u8 = @intCast(a);
    _ = b;
}

Shell

$ zig test test_intCast_builtin.zig
1/1 test_intCast_builtin.test.integer cast panic... thread 990176 panic: integer cast truncated bits
/home/ci/actions-runner/_work/zig-bootstrap/zig/docgen_tmp/test_intCast_builtin.zig:4:19: 0x1038e82 in test.integer cast panic (test)
    const b: u8 = @intCast(a);
                  ^
/home/ci/actions-runner/_work/zig-bootstrap/out/host/lib/zig/compiler/test_runner.zig:158:25: 0x1044282 in mainTerminal (test)
        if (test_fn.func()) |_| {
                        ^
/home/ci/actions-runner/_work/zig-bootstrap/out/host/lib/zig/compiler/test_runner.zig:35:28: 0x103a26b in main (test)
        return mainTerminal();
                           ^
/home/ci/actions-runner/_work/zig-bootstrap/out/host/lib/zig/std/start.zig:501:22: 0x10393a9 in posixCallMainAndExit (test)
            root.main();
                     ^
/home/ci/actions-runner/_work/zig-bootstrap/out/host/lib/zig/std/start.zig:253:5: 0x1038f11 in _start (test)
    asm volatile (switch (native_arch) {
    ^
???:?:?: 0x0 in ??? (???)
error: the following test command crashed:
/home/ci/actions-runner/_work/zig-bootstrap/out/zig-local-cache/o/2692afe223c7b62e0d699882f8c4b15a/test

To truncate the significant bits of a number out of range of the destination type, use @truncate.

If T is comptime_int, then this is semantically equivalent to Type Coercion.