const std = @import("std"); const BinaryEncoder = struct { buf: []u8, byte_index: usize = 0, bit_index: u8 = 0, pub fn init(buf: []u8) BinaryEncoder { const be = BinaryEncoder{ .buf = buf }; @memset(buf, 0); return be; } pub fn write(this: *@This(), value: u8, bit_width: u8) void { const shift_left: u3 = @intCast(this.bit_index); this.buf[this.byte_index] |= value << shift_left; if (this.bit_index + bit_width > 8) { const shift_right: u3 = @intCast(8 - this.bit_index); this.buf[this.byte_index + 1] |= value >> shift_right; this.bit_index = bit_width - shift_right; } else if (this.bit_index + bit_width == 8) { this.bit_index = 0; this.byte_index += 1; } else { this.bit_index += bit_width; } } }; pub fn main() !void { var buf: [16]u8 = undefined; var be = BinaryEncoder.init(&buf); be.write(0b0000000, 7); be.write(0b11, 2); std.debug.print("val: bin:{b} dec:{}\n", .{ buf[0], buf[0] }); std.debug.print("val: bin:{b} dec:{}\n", .{ buf[1], buf[1] }); }