LZW compression on C# from string

后端 未结 3 1080
说谎
说谎 2021-01-25 21:17

I\'m looking for a LZW compression algorithm in C# that takes a \"string\" and returns a string. I\'ve googling for hours and all I\'ve found use MemoryStream, BinaryWriters, et

相关标签:
3条回答
  • 2021-01-25 21:55

    Given that LZW codes needn't necessarily fall on byte boundaries, simply converting the binary output of LZW compression to a UTF8 string (as with the StreamReader approach) will most likely fail, producing illegal output.

    It seems that the Javascript decompress function you refer to actually takes an array of numbers as its input. Probably the most efficient way to convey the binary output to the javascript decompress method would be to base64 encode the binary output, then to base64 decode at the JS end into a number array and to supply this to your method.

    This might be of questionable efficiency. Worth testing before deploying.

    0 讨论(0)
  • 2021-01-25 22:04

    You can "convert" a string into a MemoryStrem like this:

    byte[] byteArray = Encoding.ASCII.GetBytes(youInputString);
    MemoryStream stream = new MemoryStream(byteArray);
    

    (make sure you understand which encoding you need).

    The other way goes like this:

    StreamReader reader = new StreamReader(methodOutputStream);
    string text = reader.ReadToEnd();
    

    To use the methods found on http://paste.lisp.org/display/12198, you can first convert your string to a Stream, feed it to the LZW compression methods, receive an output Stream, and convert that stream to a string. The only difference is that the code on the site uses FileStreams.

    0 讨论(0)
  • 2021-01-25 22:07

    Use something like this:

    private string CompressToLZW(string input)
    {
        using (MemoryStream stream = new MemoryStream())
        {
            ComputeLZW(input, stream);
            stream.Seek(0, SeekOrigin.Begin);
            using (StreamReader reader = new StreamReader(stream))
            {
                return reader.ReadToEnd();
            }
        }
    }
    

    where ComputeLZW() is the LZW method you have that uses a stream.

    0 讨论(0)
提交回复
热议问题