creating very small types

Michael Spencer mahs at telcopartners.com
Wed Apr 27 18:54:54 EDT 2005


andrea wrote:
>>>I was thinking to code the huffman algorithm and trying to compress
>>>something with it, but I've got a problem.
>>>How can I represent for example a char with only 3 bits??

>>>I had a look to the compression modules but I can't understand them much...
...
> I understand I can't do it easily in python, but maybe I could define a
> new type in C and use it to do those dirty works, what do you think?

Why do you need to create 'very small types'?

You only need actual bit-twiddling when you do the encoding/de-coding right?
If you create an encoding map 'codes' as a dict of strings of '1' and '0', 
encoding might look like (untested):


     def encode(stream):
         outchar = count = 0
         for char in stream:
             for bit in codes[char]:
                 (outchar << 1) | (bit == "1")
                 count +=1
                 if count ==8:
                     yield chr(outchar)
                     outchar = count = 0
         if count:
             yield chr(outchar)


HTH
Michael




More information about the Python-list mailing list