我對壓縮算法瞭解不多。我正在尋找一種簡單的壓縮算法(或代碼片段),它可以減小字節[,,]或字節[]的大小。我無法使用System.IO.Compression。此外,數據有很多重複。C#壓縮字節數組
我試着實現RLE算法(下面貼出來供您檢查)。但是,它會產生1.2到1.8倍的數組。
public static class RLE
{
public static byte[] Encode(byte[] source)
{
List<byte> dest = new List<byte>();
byte runLength;
for (int i = 0; i < source.Length; i++)
{
runLength = 1;
while (runLength < byte.MaxValue
&& i + 1 < source.Length
&& source[i] == source[i + 1])
{
runLength++;
i++;
}
dest.Add(runLength);
dest.Add(source[i]);
}
return dest.ToArray();
}
public static byte[] Decode(byte[] source)
{
List<byte> dest = new List<byte>();
byte runLength;
for (int i = 1; i < source.Length; i+=2)
{
runLength = source[i - 1];
while (runLength > 0)
{
dest.Add(source[i]);
runLength--;
}
}
return dest.ToArray();
}
}
我還發現了一個基於java,string和integer的LZW實現。我已將其轉換爲C#,結果看起來不錯(代碼如下)。但是,我不確定它是如何工作的,也不知道如何使它與字節而不是字符串和整數一起工作。
public class LZW
{
/* Compress a string to a list of output symbols. */
public static int[] compress(string uncompressed)
{
// Build the dictionary.
int dictSize = 256;
Dictionary<string, int> dictionary = new Dictionary<string, int>();
for (int i = 0; i < dictSize; i++)
dictionary.Add("" + (char)i, i);
string w = "";
List<int> result = new List<int>();
for (int i = 0; i < uncompressed.Length; i++)
{
char c = uncompressed[i];
string wc = w + c;
if (dictionary.ContainsKey(wc))
w = wc;
else
{
result.Add(dictionary[w]);
// Add wc to the dictionary.
dictionary.Add(wc, dictSize++);
w = "" + c;
}
}
// Output the code for w.
if (w != "")
result.Add(dictionary[w]);
return result.ToArray();
}
/* Decompress a list of output ks to a string. */
public static string decompress(int[] compressed)
{
int dictSize = 256;
Dictionary<int, string> dictionary = new Dictionary<int, string>();
for (int i = 0; i < dictSize; i++)
dictionary.Add(i, "" + (char)i);
string w = "" + (char)compressed[0];
string result = w;
for (int i = 1; i < compressed.Length; i++)
{
int k = compressed[i];
string entry = "";
if (dictionary.ContainsKey(k))
entry = dictionary[k];
else if (k == dictSize)
entry = w + w[0];
result += entry;
// Add w+entry[0] to the dictionary.
dictionary.Add(dictSize++, w + entry[0]);
w = entry;
}
return result;
}
}
「我無法使用System.IO.Compression」 - 爲什麼? – 2010-07-17 02:23:11
擴大一點米奇說,還有其他庫(如[SharpZipLib](http://www.icsharpcode。net/opensource/sharpziplib /)),所以理解爲什麼你不能在框架中使用現有的東西將有助於找出哪些其他選項可能起作用 – 2010-07-17 02:49:21
那麼,它在我的平臺(xbox 360)上不可用。 – zfedoran 2010-07-17 02:49:47