Comptime number of bits for u(N) integer

Hey folks.

I’m working on updating the bindings of a C library (zflecs) and encountered this code:

/* Bitmask type with compile-time defined size */
#define ecs_flagsn_t_(bits) ecs_flags##bits##_t
#define ecs_flagsn_t(bits) ecs_flagsn_t_(bits)

/* Bitset type that can store exactly as many bits as there are terms */
#define ecs_termset_t ecs_flagsn_t(FLECS_TERM_COUNT_MAX)

At compile time the ecs_term_set type is produced which defines a number of bits equal to FLECS_TERM_COUNT_MAX (which can be max 32 btw).

I usually find my way by myself around zig but this time I have no idea what syntax I could use to have the same behavior. Also, I don’t know if I can just stick an i32 and call it a day.

Is it doable in Zig as well?

Hi @giusdp welcome to ziggit :slight_smile:

Are you aware of zflecs?


The following function returns the unsigned integer type for the number of bits.
e.g. ecs_flagsn_t(16) returns u16
You can use the function call in place of any type.
e.g. const foo: ecs_flagsn_t(16) = 0;

pub fn ecs_flagsn_t(comptime bits: u16) type {
    return std.meta.Int(.unsigned, bits);
}
2 Likes

Thank you so much. Pretty cool function, no idea I could do that :slight_smile:

I actually think I’m updating that library but on the zig-gamedev repo. I don’t know if it’s the same one tbh.
Anyway thanks for the swift response, I’ll mark it as solution.

1 Like