bits_reader


bits_reader(r)
      

Return a bits reader that read bits from the stream reader r.

Examples:

Bit streams are for reading and writing data at bit-level. As a simple example of bit encoded data, consider 16-bit color values. In 16-bit color, the red and blue components are encoded using 5-bits each, while the green component takes up 6-bit. The following program reads and writes 16-bit encoded color values:


function encode_color(rgb)
  let (out = byte_array_writer(),
       encoder = bits_writer(out))
  { write_bits(encoder, rgb['red], 5)
    write_bits(encoder, rgb['green], 6)
    write_bits(encoder, rgb['blue], 5)
    bits_writer_flush(encoder)
    get_output_bytes(out) }

function decode_color(color)
  let (in = byte_array_reader(color),
          decoder = bits_reader(in),
          r = read_bits(decoder, 5),
          g = read_bits(decoder, 6),
          b = read_bits(decoder, 5))
      #{'red: r, 'green: g, 'blue: b}

decode_color(encode_color(#{'red: 12, 'green: 51, 'blue: 20}))
// #{red: 12, green: 51, blue: 20}
      

Also see:

file_reader


Core Module Index | Contents