Search code examples
zig

@bitCast only accepting one argument while documentation lists two


I'm attempting to cast a u8 to a packed struct. The Builtin function @bitCast seems to be the tool for the job.

According to the documentation it should let me change type but maintain bit representation.

I also found an example of what I'm trying to achieve in a blogpost.

const std = @import("std");
const print = std.debug.print;

const mystruct  = packed struct {
    a : u16,
    b : u16,
};

pub fn main() void {
    const s2  :mystruct =   .{ .a = 10, .b = 20};
    const s3 : u32 = @bitCast(u32, s2);
    const s4 : mystruct = @bitCast(mystruct, s3);
    print("{}\n", .{ s4});
}

However no matter what I try the compiler keeps telling me @bitCast only takes one argument while the example above and the documentation explicitly list it requires two arguments.

For example when running the above code the compiler tells me:

src/main.zig:90:22: error: expected 1 argument, found 2
    const s3 : u32 = @bitCast(u32, s2);
                     ^~~~~~~~~~~~~~~~~

What am I doing wrong? It makes total sense to me that @bitCast should require two arguments.

I'm using Zig 0.13.0.


Solution

  • The blog post is outdated. Call @bitCast like this:

    const s3: u32 = @bitCast(s2);
    

    Or like this:

    const s3 = @as(u32, @bitCast(s2));
    

    In Zig 0.11+, the builtins have been updated to use Result Location Semantics (see also this answer).