#packed struct as integer (bit field)

1 messages · Page 1 of 1 (latest)

dusky mauve
#

So I tried using packed structs for my bit fields, and I am a bit stuck on how to use them properly.
My example code:

pub const pin = packed struct(u8) {
    p0: bool = false,
    p1: bool = false,
    p2: bool = false,
    p3: bool = false,
    p4: bool = false,
    p5: bool = false,
    p6: bool = false,
    p7: bool = false,

    pub fn val(self: pin) u8 {
        return @bitCast(self);
    }
};

const gpio_s = packed struct {
    pin: u8,
    dir: u8,
    port: u8,
};

pub const gpio: *volatile gpio_s = @ptrFromInt(0x23);


export fn app_main() void {
    var pp = pin.val(.{ .p5 = true });
    gpio.dir |= pp;
    while (true) {
        gpio.port ^= pp;

        // dump loop
        for (0..1000) |_| {
            for (0..200) |_| {
                asm volatile ("nop");
            }
        }
    }
}

What I want to do is basically what we do in C but nicer, e.g. either gpio.dir |= pin.p5 | pin.p6 | ... or (what I tried to do now) gpio.dir |= pin.val( .{ .p5 = true }); but that didn't work, instead I had to save struct as a temporary variable, pp in this case, and then do gpio.dir |= pp which is not as neat. Why do I have to save the value in a variable first?

Also, is there an even nicer/cleaner way of doing this?

drifting bane
#

the struct type pin doesn't have a decl named p5, which is what you're trying to access with pin.p5. p5 is a field of the struct instance. you should be able to do gpio.dir |= pin.val(.{ .p5 = true });

opaque sail
#

why not make the fields of gpio_s pin? then you could just gpio.dir.p5 = true

#

doing this bit stuff defeats the purpose of using packed structs at all imo

dusky mauve
dusky mauve
opaque sail
#

i guess you wouldnt, no

dusky mauve