Why do packed struct reverse the order of u4 fields?

test "thing" {
	const x: packed struct {
		x: u4, y:u4,
	} = .{.x = 0xf, .y = 0xe};
	print("{x}\n", .{std.mem.asBytes(&x)});
}

So this piece of code should give me { fe } as an output since we are supposed to control the bit order in packed structs right ?

But I get { ef } instead.

Can someone explain to me why this happens ? I’ve only tested u4s, so I don’t know if it happens with other sizes, but why does this reversing happen at all ?

I don’t think it’s because of endianess. I’m on a little endian system, and doing the same thing with a packed struct with u8s is fine, the order is maintained.

packed struct fields are ordered starting at the least significant bit. So the x field is at bit 0, and the y fields is at bit 4 of the underlying integer. I think this makes a lot of sense, because that’s how you would define them if you were just manually making the bitfield x | y << 4.

The fact that it accidentally produces the same ordering as the underlying bytes if you use a u8 is because of endianness. On a big endian system you’d likely see the opposite results.

I see. Thank you !