You put bits into an int in multiples of 20, and take them out in multiples of 8.

If any bits are left afterwards, you flush out the remainder.

Like this:

Code:

unsigned int bitsHeld=0, bits=0;
pack20BitsOf(int val)
{
bitsHeld += 20;
bits = (bits << 20) | val;
while (bitsHeld >= 8)
{
bitsHeld -= 8;
writeoutByte(bits >> bitsHeld);
bits ^= (bits >> bitsHeld) << bitsHeld;
}
}
flushBits()
{
if (bitsHeld > 0)
{
writeoutByte(bits << (8-bitsHeld));
bits = 0;
bitsHeld = 0;
}
}

or if you want to pack the bits in the other order (which may be a little bit simpler), then like this:

Code:

unsigned int bitsHeld=0, bits=0;
pack20BitsOf(int val)
{
bitsHeld += 20;
bits |= val << bitsHeld;
while (bitsHeld >= 8)
{
bitsHeld -= 8;
writeoutByte(bits & 0xFF);
bits >>= 8;
}
}
flushBits()
{
if (bitsHeld > 0)
{
writeoutByte(bits & 0xFF);
bits = 0;
bitsHeld = 0;
}
}