public List <int> Unpack(List <byte> packedBytes) { List <int> codeStream = new List <int>(); List <byte> tempPackedBytes = new List <byte>(); tempPackedBytes.AddRange(packedBytes); List <bool> bitStream = new List <bool>(); int currentCodeWidth = LzwMinimumCodeSize + 1; int codeWidthIncreaseThreshold = (int)Math.Pow(2, currentCodeWidth) - 1; for (int i = 0; i < tempPackedBytes.Count; i++) { tempPackedBytes[i] = tempPackedBytes[i].ReverseByte(); // big endian List <bool> bits = GlobalUtilities.ConvertByteToBits(tempPackedBytes[i], 8); bits.Reverse(); bitStream.AddRange(bits); } for (int i = 0; i < bitStream.Count; i += 0) { if (codeStream.Count >= codeWidthIncreaseThreshold) { currentCodeWidth++; codeWidthIncreaseThreshold = (int)Math.Pow(2, currentCodeWidth) - 1; } if (i + currentCodeWidth < bitStream.Count) { List <bool> chunk = bitStream.GetRange(i, currentCodeWidth); chunk.Reverse(); int code = GlobalUtilities.ConvertBitsToInt(chunk); codeStream.Add(code); } i += currentCodeWidth; } return(codeStream); }
public List <byte> Pack(List <int> codeStream) { List <byte> packedBytes = new List <byte>(); List <bool> bits = new List <bool>(); int currentCodeWidth = LzwMinimumCodeSize + 1; int codeCount = 0; int codeWidthIncreaseThreshold = (int)Math.Pow(2, currentCodeWidth) - 1; foreach (int code in codeStream) { if (codeCount >= codeWidthIncreaseThreshold) { currentCodeWidth++; codeWidthIncreaseThreshold = (int)Math.Pow(2, currentCodeWidth) - 1; } List <bool> codeBits = GlobalUtilities.ConvertIntToBits(code, currentCodeWidth); bits.AddRange(codeBits); codeCount++; } int zeroesNeeded = 8 - (bits.Count % 8); for (int i = 0; i < zeroesNeeded; i++) { bits.Add(false); } for (int i = 0; i < bits.Count; i += 8) { List <bool> reversedByte = bits.GetRange(i, 8); reversedByte.Reverse(); packedBytes.Add(GlobalUtilities.ConvertBitsToByte(reversedByte.ToArray())); } return(packedBytes); }