outbits.icn: Procedure to write variable-length characters

link outbits
November 3, 1991; Richard L. Goerwitz
See also: inbits.icn
This file is in the public domain.

In any number of instances (e.g. when outputting variable-length
characters or fixed-length encoded strings), the programmer must
fit variable and/or non-byte-sized blocks into standard 8-bit
bytes.  Outbits() performs this task.

Pass to outbits(i, len) an integer i, and a length parameter (len),
and outbits will suspend byte-sized chunks of i converted to
characters (most significant bits first) until there is not enough
left of i to fill up an 8-bit character.  The remaining portion is
stored in a buffer until outbits() is called again, at which point
the buffer is combined with the new i and then output in the same
manner as before.  The buffer is flushed by calling outbits() with
a null i argument.  Note that len gives the number of bits there
are in i (or at least the number of bits you want preserved; those
that are discarded are the most significant ones).

A trivial example of how outbits() might be used:

    outtext := open("some.file.name","w")
    l := [1,2,3,4]
    every writes(outtext, outbits(!l,3))
    writes(outtext, outbits(&null,3))           # flush buffer

List l may be reconstructed with inbits() (see inbits.icn):

    intext := open("some.file.name")
    l := []
    while put(l, inbits(intext, 3))

Note that outbits() is a generator, while inbits() is not.

Source code | Program Library Page | Icon Home Page