Skip to content

Zig Packed & Extern Structs

Most of the time you don’t care how a struct sits in memory, and Zig is happy to decide for you. But some jobs need exact control. A byte where each bit is an on/off switch. A hardware register. The header of a file format. A struct you hand to a C library, which expects its fields in a precise order. For these, Zig has two special kinds of struct: packed struct, where fields are laid out bit by bit, and extern struct, which follows C’s rules. This page shows when you need each, and why you usually don’t.

For a normal struct, Zig makes no promises about field order or size. It’s allowed to move fields around to waste less space. You can see this with @sizeOf (size in bytes) and @offsetOf (where a field starts):

const std = @import("std");
const Normal = struct {
a: u8,
b: u32,
c: u8,
};
const LikeC = extern struct {
a: u8,
b: u32,
c: u8,
};
pub fn main() void {
std.debug.print("Normal: {d} bytes, a at {d}, b at {d}, c at {d}\n", .{
@sizeOf(Normal), @offsetOf(Normal, "a"), @offsetOf(Normal, "b"), @offsetOf(Normal, "c"),
});
std.debug.print("LikeC: {d} bytes, a at {d}, b at {d}, c at {d}\n", .{
@sizeOf(LikeC), @offsetOf(LikeC, "a"), @offsetOf(LikeC, "b"), @offsetOf(LikeC, "c"),
});
}

Output:

Normal: 8 bytes, a at 4, b at 0, c at 5
LikeC: 12 bytes, a at 0, b at 4, c at 8

The normal struct put b first, then a and c behind it, and fits in 8 bytes. The extern struct keeps the order you wrote, like C does. Since a u32 must start at a multiple of 4, C’s rules leave 3 empty bytes after a and more at the end, so it takes 12. These numbers are from 64-bit Linux and can differ on other targets, and for the normal struct they could change in a future Zig version. That’s the point: if you don’t need a fixed layout, let Zig choose.

A packed struct puts its fields right next to each other, bit by bit, with no gaps. Each field uses exactly as many bits as its type: a bool takes 1 bit, a u3 takes 3. The classic use is a set of on/off flags in one byte:

const std = @import("std");
const Permissions = packed struct(u8) {
read: bool,
write: bool,
execute: bool,
_unused: u5 = 0,
};
pub fn main() void {
const p: Permissions = .{ .read = true, .write = false, .execute = true };
std.debug.print("read: {}, write: {}\n", .{ p.read, p.write });
std.debug.print("{d} byte, {d} bits\n", .{ @sizeOf(Permissions), @bitSizeOf(Permissions) });
}

Output:

read: true, write: false
1 byte, 8 bits

Three flags plus 5 unused bits fill exactly one byte, and you work with them by name: p.read, not (byte >> 0) & 1. @bitSizeOf gives the size in bits.

The (u8) after packed struct is the backing integer: the integer the whole struct is stored as. The fields must add up to exactly its size, which is why _unused: u5 = 0 is there. The default value means nobody has to set it. The name is up to you; a leading _ just signals “don’t touch”. The language reference on packed structs has every rule.

If you write a backing integer, Zig checks the total for you:

const Flags = packed struct(u8) {
a: bool,
b: bool,
c: u4,
};
pub fn main() void {
const f: Flags = .{ .a = true, .b = false, .c = 0 };
_ = f;
}
main.zig:1:22: error: backing integer bit width does not match total bit width of fields
const Flags = packed struct(u8) {
~~~~~~~^~~~~~
main.zig:1:29: note: backing integer 'u8' has bit width '8'
const Flags = packed struct(u8) {
^~
main.zig:1:22: note: struct fields have total bit width '6'

Six bits of fields, but you promised eight. Add a u2 field, or change the backing type. You can also leave the (u8) off, and Zig picks an unsigned integer of the right size (a u6 here). Writing it out is clearer, and as you’ll see next, Zig 0.17’s new conversion builtins need it.

Fields have to be things that have a fixed number of bits: integers of any width, bool, other packed structs, and enums with an explicit tag type like enum(u2). A slice or a normal struct doesn’t fit:

const Bad = packed struct {
id: u8,
name: []const u8,
};
pub fn main() void {
const b: Bad = .{ .id = 1, .name = "x" };
_ = b;
}
main.zig:3:11: error: packed structs cannot contain fields of type '[]const u8'
name: []const u8,
^~~~~~~~~~
main.zig:3:11: note: slices do not have a bit-packed representation

To and from the integer: @backingInt and @fromBackingInt

Section titled “To and from the integer: @backingInt and @fromBackingInt”

A packed struct is really just its backing integer with names for the bits. Zig 0.17 added two builtins to switch between the two views:

const std = @import("std");
const Permissions = packed struct(u8) {
read: bool,
write: bool,
execute: bool,
_unused: u5 = 0,
};
pub fn main() void {
const p: Permissions = .{ .read = true, .write = false, .execute = true };
const byte = @backingInt(p);
std.debug.print("as a byte: {b:0>8} ({d})\n", .{ byte, byte });
const q: Permissions = @fromBackingInt(@as(u8, 0b0000_0011));
std.debug.print("read: {}, write: {}, execute: {}\n", .{ q.read, q.write, q.execute });
}

Output:

as a byte: 00000101 (5)
read: true, write: true, execute: false

The first field is the lowest bit. read is bit 0 (the rightmost digit), write bit 1, execute bit 2. So read plus execute is 101 in binary, which is 5. Going back, 0b0000_0011 has the two lowest bits set: read and write. {b:0>8} prints a number in binary, padded to 8 digits, as covered in Zig Format Strings.

@fromBackingInt takes exactly the backing type, so the u8 is spelled out with @as. These are the same two builtins that replaced @intFromEnum and @enumFromInt for enums.

Small screens often store a color in 16 bits: 5 bits of red, 6 of green, 5 of blue (called RGB565). Packing that by hand takes shifts and masks that are easy to get wrong. A packed struct does it for you. Remember that the first field is the lowest bits, so blue comes first:

const std = @import("std");
const Rgb565 = packed struct(u16) {
blue: u5,
green: u6,
red: u5,
};
pub fn main() void {
const red: Rgb565 = .{ .red = 31, .green = 0, .blue = 0 };
const white: Rgb565 = .{ .red = 31, .green = 63, .blue = 31 };
std.debug.print("red = 0x{X:0>4}\n", .{@backingInt(red)});
std.debug.print("white = 0x{X:0>4}\n", .{@backingInt(white)});
var c = white;
c.green = 0;
std.debug.print("magenta = 0x{X:0>4}\n", .{@backingInt(c)});
}

Output:

red = 0xF800
white = 0xFFFF
magenta = 0xF81F

0xF800 is the value you’ll find in any RGB565 color table for pure red, and you didn’t write a single shift. Setting c.green = 0 changes just those six bits. You can also compare two packed structs with == and !=; Zig compares their backing integers.

An extern struct lays out its fields the way C would on the target you’re building for: in the order you wrote them, with the same padding a C compiler adds. Use it when the memory has to match something outside Zig: a struct you pass to or get from a C library, or a binary file format.

const std = @import("std");
const FileHeader = extern struct {
magic: [4]u8,
version: u16,
flags: u16,
size: u32,
};
pub fn main() void {
const header: FileHeader = .{
.magic = "ZIG!".*,
.version = 1,
.flags = 0,
.size = 4096,
};
std.debug.print("{d} bytes, size starts at byte {d}\n", .{ @sizeOf(FileHeader), @offsetOf(FileHeader, "size") });
const bytes = std.mem.asBytes(&header);
std.debug.print("{x}\n", .{bytes});
}

Output:

12 bytes, size starts at byte 8
5a4947210100000000100000

std.mem.asBytes gives you a view of the struct’s memory as bytes. You can see 5a494721 (“ZIG!”), then 0100 for version 1, 0000 for the flags, and 00100000 for 4096. The numbers come out “backwards” (low byte first) because this machine is little-endian, which most computers today are. If a file format says “big-endian”, you have to swap the bytes yourself; std.mem has helpers like std.mem.nativeToBig.

Like packed structs, extern structs only take fields C understands: numbers, bool, arrays, pointers, and other extern structs. A slice is rejected with extern structs cannot contain fields of type '[]const u8', because C has no slices. For C text you’d use a pointer like [*:0]const u8; see Zig Sentinel-Terminated Types.

You want Use
Just to group some data (almost always) struct
Named bits or small fields inside one integer: flags, registers, colors packed struct(uN)
The same layout a C compiler would use: C libraries, binary file headers extern struct

Packed and extern structs give up something for their fixed layout. Packed fields can be slower to read (Zig has to shift and mask), and extern structs can’t hold slices or Zig-only types. So reach for them when the layout matters, not by default. Enums and unions have extern and packed versions too, following the same ideas; see extern union in the reference.

Make a packed struct(u8) called Modifiers with shift, ctrl, alt and super as bools, plus padding. Create one with ctrl and alt pressed and print its byte in binary.

Hint: four bools are 4 bits, so the padding is a u4 with a default of 0. ctrl is the second field, so it’s bit 1.

Show solution
const std = @import("std");
const Modifiers = packed struct(u8) {
shift: bool = false,
ctrl: bool = false,
alt: bool = false,
super: bool = false,
_unused: u4 = 0,
};
pub fn main() void {
const keys: Modifiers = .{ .ctrl = true, .alt = true };
std.debug.print("{b:0>8}\n", .{@backingInt(keys)});
}

Output:

00000110

Giving every field a default means you only name the keys that are pressed. Bits 1 and 2 are set, read from the right.

A device sends a status byte. Bit 0 says whether it’s powered on, bits 1 to 3 are an error code (0 to 7), and bits 4 to 7 are a battery level (0 to 15). Turn the byte 0b1010_0101 into a packed struct and print the three values.

Hint: field order is lowest bit first: on: bool, then error_code: u3, then battery: u4. Use @fromBackingInt with a u8.

Show solution
const std = @import("std");
const Status = packed struct(u8) {
on: bool,
error_code: u3,
battery: u4,
};
pub fn main() void {
const raw: u8 = 0b1010_0101;
const s: Status = @fromBackingInt(raw);
std.debug.print("on: {}, error: {d}, battery: {d}\n", .{ s.on, s.error_code, s.battery });
}

Output:

on: true, error: 2, battery: 10

The low bit is 1, so on is true. The next three bits are 010, which is 2. The top four are 1010, which is 10. No shifting or masking needed.

Without running it, guess @sizeOf for both structs, then check.

const A = struct { flag: bool, value: u64, other: bool };
const B = extern struct { flag: bool, value: u64, other: bool };

Hint: Zig can reorder A. B keeps the order, and a u64 must start at a multiple of 8.

Show solution
const std = @import("std");
const A = struct { flag: bool, value: u64, other: bool };
const B = extern struct { flag: bool, value: u64, other: bool };
pub fn main() void {
std.debug.print("A: {d} bytes\n", .{@sizeOf(A)});
std.debug.print("B: {d} bytes\n", .{@sizeOf(B)});
}

Output:

A: 16 bytes
B: 24 bytes

B needs 7 bytes of padding after flag so value starts at byte 8, and 7 more at the end so the next B in an array lines up too. Zig moved A’s two bools next to each other after value, which saves 8 bytes. (On this 64-bit Linux machine; other targets can differ.)

  • A normal struct has no guaranteed layout: Zig may reorder fields and pick the size.
  • A packed struct(uN) stores its fields bit by bit inside one integer, first field in the lowest bits.
  • The fields must add up to the backing integer exactly; packed fields must be integers, bools, packed structs or enums with an explicit tag type.
  • @backingInt and @fromBackingInt (new in 0.17, need an explicit backing type) or @bitCast convert to and from the integer.
  • An extern struct uses C’s layout: your field order plus C’s padding. No slices allowed.
  • In Zig 0.17 you can’t @bitCast an extern struct; use std.mem.asBytes or @ptrCast.
  • Use packed and extern structs only when the layout matters.

Next up: Zig Opaque Types, for handles to things whose insides you’re not allowed to see.

Quick check

1. In packed struct(u8) { a: bool, b: bool, rest: u6 }, which bit does a use?
2. Why does packed struct(u8) { a: bool, b: u4 } fail to build?
3. You need a struct whose memory matches a struct in a C header. What do you use?
4. In Zig 0.17, what happens with const n: u32 = @bitCast(my_extern_struct);?