使用静态Huffman压缩的数据块,在数据块的开头仍然是3个bit的Header,第2个bit是1、第3个bit是0,因为读取过程是先读取低位,再读取高位,所以结果应该是二进制01。
接下来的数据就是被压缩的数据,因为静态Huffman的h1(编码literal和length)是固定的,不需要记录压缩过程的信息:
初始过程:
Private Function InitFixedHuffmanTree() Dim i As Long Dim arr() As Long ReDim arr(287) As Long For i = 0 To 143 arr(i) = 8 Next For i = 144 To 255 arr(i) = 9 Next For i = 256 To 279 arr(i) = 7 Next For i = 280 To 287 arr(i) = 8 Next Set hFixed = CreateHuffman(arr) Erase arrEnd Functio
h2(编码distance)不需要,直接固定按5个bit来编码。
解压过程:
'静态Huffman
Private Function InflateByFixedHuffman(ByRef cpByte() As Byte, ByRef uncpByte() As Byte, ByRef bitIndex As Long, ByRef pUncp As Long)
Dim ilen As Long
Dim iDistance As Long
Dim i As Long
Dim bValue As Long
'按hFixed解码一个数字
bValue = hFixed.GetLeafKey(cpByte, bitIndex)
Do Until bValue = 256
If bValue < 256 Then
uncpByte(pUncp) = bValue
pUncp = pUncp + 1
Else
ilen = bValue - 257
ilen = ExtraValue(ilen, LengthCode, cpByte, bitIndex)
'Distance来说,需要对Code=0-29的数进行编码,则直接采用5比特表示
iDistance = GetBitsRev(cpByte, bitIndex, 5)
bitIndex = bitIndex + 5
iDistance = ExtraValue(iDistance, DistanceCode, cpByte, bitIndex)
'根据长度和距离复制数据
For i = 1 To ilen
uncpByte(pUncp) = uncpByte(pUncp - iDistance)
' Debug.Print pUncp, VBA.Hex(uncpByte(pUncp))
pUncp = pUncp + 1
Next
End If
bValue = hFixed.GetLeafKey(cpByte, bitIndex)
Loop
End Function
静态Huffman解压过程要特别注意的是iDistance的5bit编码,在前面读取Header、HLIT、HDIST、HCLEN以及CCL的时候,都是先读取低位,再读取高位,然后组合为一个整数。
iDistance的5bit读取过程自然还是一样的,但是它的编码却是相反的,先读取出来的低位要放置到最高位。