On Thu, May 17, 2007 at 09:52:51PM +0900, Richard Fairhurst wrote:
> I'm writing a bit of Ruby to output SWF files.
> 
> SWF's opcodes and arguments are variable-length streams of bits. They're
> packed in direct succession - i.e. not usually padded to byte
> boundaries.
> 
> So, for example, you might have
> 
>    00111         5-bit record
>    0110101       7-bit record
>    0000110       7-bit record
>    0001100       7-bit record
>    1111101       7-bit record
> 
> which would be packed as
> 
>    0b00111011,0b01010000,0b11000011,0b00111110,0b10000000
> 
> (the final byte here is null-padded)
> 
> I'm trying to write these opcode by opcode, and get a bytestream out the
> end of it. Currently I'm just appending each opcode to a long string
> (m+='00111'), and when it comes to writing it out, splitting this every
> eight characters and converting back to a single character. But this is
> awfully slow.
> 
> Can anyone suggest a faster way?

Hmm, sounds like Huffman coding... see Ruby Quiz just gone :-)

If speed is critical it might be worth writing a C extension to do it.