Bitstream I/O

medium · compression, bit-io, encoding

Bitstream I/O

Implement MSB-first bit-level writing and reading.

Types

type BitWriter struct {
    // implement fields
}

type BitReader struct {
    // implement fields
}

func NewBitWriter() *BitWriter
func (bw *BitWriter) WriteBit(bit uint8)
func (bw *BitWriter) WriteBits(value uint64, n int)
func (bw *BitWriter) Bytes() []byte

func NewBitReader(data []byte) *BitReader
func (br *BitReader) ReadBit() (uint8, bool)
func (br *BitReader) ReadBits(n int) (uint64, bool)

Bit order (MSB-first)

  • The first bit written goes to the highest bit of the first byte (bit 7).
  • WriteBits(value, n) writes the n lowest bits of value, from MSB to LSB.
  • Padding: if the stream ends mid-byte, pad remaining low bits with zeros.

Read behavior

  • ReadBit returns (bit, ok); ok=false if no more bits.
  • ReadBits(n) returns (value, ok); ok=false if fewer than n bits remain.

Notes

  • Bytes() should return a copy of the written bytes.
  • ReadBits should assemble bits in the same order they were written.
Run tests to see results
No issues detected