Python Bitstream implementations

前端 未结 4 2030
长发绾君心
长发绾君心 2021-01-04 19:49

I am writing a huffman implementation in Python as a learning exercise. I have got to the point of writing out my variable length huffman codes to a buffer (or file). Only

4条回答
  •  长发绾君心
    2021-01-04 20:06

    No, as far as I know there's nothing in the standard library that helps you with bit-aligned operations. Python is not designed to fiddle with the small stuff ^^...

    But you could easily write your own bitstream-writer with the help of byte arrays:

    >>> from array import array
    >>> a = array("B")
    >>> a.append(1) # 128
    >>> a.append(0)
    >>> a.append(0)
    >>> a.append(0)
    >>> a.append(1) # 8
    >>> a.append(1) # 4
    >>> a.append(1) # 2
    >>> a.append(1) # 1
    >>> print reduce(lambda m, n: (m << 1) + n, a, 0)
    143
    

    You get the idea...

提交回复
热议问题