Advertisement
Guest User

Keen LZW Decompressor in VB.NET

a guest
Dec 24th, 2013
162
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
VB.NET 2.29 KB | None | 0 0
  1. Function DecompressLZW(Data As IO.Stream, MaxBits As Byte) As IO.MemoryStream
  2.         Dim out As New IO.MemoryStream
  3.         Dim dict As New List(Of String)
  4.         For x = 0 To 255
  5.             dict.Add(Chr(x))
  6.         Next
  7.         dict.Add("")
  8.         dict.Add(Nothing)
  9.         Dim usebits As Byte = 9
  10.         Dim bpos As Long
  11.         Dim bits As New List(Of Boolean)
  12.         Do Until Data.Position = Data.Length
  13.             Dim b, ub As Byte
  14.             b = Data.ReadByte
  15.             ub = b
  16.             For x = 7 To 0 Step -1
  17.                 If ub - (2 ^ x) >= 0 Then
  18.                     ub -= (2 ^ x)
  19.                     bits.Add(True)
  20.                 Else
  21.                     bits.Add(False)
  22.                 End If
  23.             Next
  24.         Loop
  25.         Dim GetCode = Function() As UInteger
  26.                           Dim u As UInteger
  27.                           For x = usebits To 1 Step -1
  28.                               If bits(bpos) Then u += (2 ^ (x - 1))
  29.                               bpos += 1
  30.                           Next
  31.                           Return u
  32.                       End Function
  33.         Dim Output = Sub(DecompData As String)
  34.                          Dim n As UInteger = DecompData.Length
  35.                          out.Write(DecompData.Select(Function(h) CByte(Asc(h))).ToArray, 0, n)
  36.                      End Sub
  37.         Dim AddToDict = Sub(Entry As String)
  38.                             If dict.Count < (2 ^ MaxBits) Then
  39.                                 dict.Add(Entry)
  40.                                 If dict.Count = (2 ^ usebits) - 1 Then usebits = Math.Min(usebits + 1, MaxBits)
  41.                             End If
  42.                         End Sub
  43.         Dim fcode As UInteger = GetCode()
  44.         Dim match As String = dict(fcode)
  45.         Output(match)
  46.         Do
  47.             Dim ncode As UInteger = GetCode()
  48.             If ncode = 257 Then Exit Do
  49.             If ncode = 256 Then Throw New Exception
  50.             Dim nmatch As String
  51.             If ncode < dict.Count Then
  52.                 nmatch = dict(ncode)
  53.             Else
  54.                 nmatch = match & match(0)
  55.             End If
  56.             Output(nmatch)
  57.             AddToDict(match & nmatch(0))
  58.             match = nmatch
  59.         Loop
  60.         out.Position = 0
  61.         Return out
  62.     End Function
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement