#Assign packed struct to number

1 messages · Page 1 of 1 (latest)

plush field
#

Hi, is it possible to assign a packed struct to a number? I would like to achieve something like this:

const Registers = struct {
    af: packed struct(u16) {
        a: u8,
        z: u1,
        n: u1,
        h: u1,
        c: u1,
        _: u4,
    },
    bc: packed struct(u16) {
        b: u8,
        c: u8,
    },
    de: packed struct(u16) {
        d: u8,
        e: u8,
    },
    hl: packed struct(u16) {
        h: u8,
        l: u8,
    },
    sp: u16,
    pc: u16,
};

regs: Registers,

pub fn run(self: @This()) u8 {
    //  cannot assign to constant
    self.regs.af = @bitCast(@as(u16, 5));
    const a = self.regs.af.a;
    return a;
}
plush field
#

just need to make self a ptr

mint lynx
#

yeah that should work, use self: *@This() because otherwise self is const

plush field
#

and how can i increment the value of a packed struct? Like this? self.regs.bc = @bitCast(@as(u16, @bitCast(self.regs.bc)) + 1)

cinder cape
#

maybe you could make these be packed unions containing a packed struct and a u16

mint lynx
#

extern union

#

either that or add methods to the packed struct that hides the boilerplate

plush field
#

packed union works great

#
af: packed union {
    r16: u16,
    fields: packed struct(u16) {
        a: u8,
        z: u1,
        n: u1,
        h: u1,
        c: u1,
        _: u4,
    },
},
bc: packed union {
    r16: u16,
    fields: packed struct(u16) {
        b: u8,
        c: u8,
    },
},
de: packed union {
    r16: u16,
    fields: packed struct(u16) {
        d: u8,
        e: u8,
    },
},
hl: packed union {
    r16: u16,
    fields: packed struct(u16) {
        h: u8,
        l: u8,
    },
},
sp: u16,
pc: u16,