| 1 | const std = @import("std"); |
| 2 | const expectEqual = std.testing.expectEqual; |
| 3 | |
| 4 | const Full = packed struct { |
| 5 | number: u16, |
| 6 | }; |
| 7 | const Divided = packed struct { |
| 8 | half1: u8, |
| 9 | quarter3: u4, |
| 10 | quarter4: u4, |
| 11 | }; |
| 12 | |
| 13 | test "@bitCast between packed structs" { |
| 14 | try doTheTest(); |
| 15 | try comptime doTheTest(); |
| 16 | } |
| 17 | |
| 18 | fn doTheTest() !void { |
| 19 | try expectEqual(2, @sizeOf(Full)); |
| 20 | try expectEqual(2, @sizeOf(Divided)); |
| 21 | const full = Full{ .number = 0x1234 }; |
| 22 | const divided: Divided = @bitCast(full); |
| 23 | try expectEqual(0x34, divided.half1); |
| 24 | try expectEqual(0x2, divided.quarter3); |
| 25 | try expectEqual(0x1, divided.quarter4); |
| 26 | |
| 27 | const ordered: [2]u8 = @bitCast(full); |
| 28 | try expectEqual(0x34, ordered[0]); |
| 29 | try expectEqual(0x12, ordered[1]); |
| 30 | } |
| 31 | |
| 32 | // test |