Chunk data decompressing (Zlib): Difference between revisions

From wiki.vg
Jump to navigation Jump to search
imported>Gzaloprgm
(Created page with "This snippet shows how to decompress chunk data sent by 0x33 packet, using Zlib deflate. Add the Zlib library by "#include <zlib.h>" and link to it by adding -lz to the linking ...")
imported>Gzaloprgm
No edit summary
Line 40: Line 40:
   case Z_DATA_ERROR:
   case Z_DATA_ERROR:
   case Z_MEM_ERROR:
   case Z_MEM_ERROR:
       cerr << "Zlib error" << endl;
       cerr << "Zlib error: inflate()" << endl;
       return ret;
       return ret;
}               
}               
Line 47: Line 47:
//Data is now in "out" buffer
//Data is now in "out" buffer
</source>
</source>
You could also decompress the data as you get it (instead of doing it after getting the whole packet).

Revision as of 13:49, 1 August 2011

This snippet shows how to decompress chunk data sent by 0x33 packet, using Zlib deflate.

Add the Zlib library by "#include <zlib.h>" and link to it by adding -lz to the linking stage.

To use it to decompress the chunk data, you can use the following snippet:

<source lang="c"> int len = net.recvInt(); char *in = new char[len]; net.recvByteArray(in, len);

//Output memory is at most 16*16*128*2.5 bytes char *out = new char[100000];

int ret; z_stream strm;

strm.zalloc = Z_NULL; strm.zfree = Z_NULL; strm.opaque = Z_NULL; strm.avail_in = 0; strm.next_in = Z_NULL; ret = inflateInit(&strm);

if (ret != Z_OK){

  cerr << "Zlib error: inflateInit() failed" << endl;
  return -1;

}

strm.avail_in = len; strm.next_in = in; strm.avail_out = 100000; strm.next_out = out;

ret = inflate(&strm, Z_NO_FLUSH);

switch (ret) {

  case Z_NEED_DICT:
     ret = Z_DATA_ERROR;   
  case Z_DATA_ERROR:
  case Z_MEM_ERROR:
     cerr << "Zlib error: inflate()" << endl;
     return ret;

} inflateEnd(&strm); delete []in; //Data is now in "out" buffer </source>

You could also decompress the data as you get it (instead of doing it after getting the whole packet).