Chunk data decompressing (Zlib): Difference between revisions

From wiki.vg
Jump to navigation Jump to search
imported>Gzaloprgm
mNo edit summary
imported>Sprenger120
(Add pointer cast (prevent compiler errors))
 
(5 intermediate revisions by 2 users not shown)
Line 29: Line 29:


strm.avail_in = len;
strm.avail_in = len;
strm.next_in = in;
strm.next_in = (Bytef*)in;  
strm.avail_out = 100000;
strm.avail_out = 100000;
strm.next_out = out;
strm.next_out = (Bytef*)out;  


ret = inflate(&strm, Z_NO_FLUSH);
ret = inflate(&strm, Z_NO_FLUSH);

Latest revision as of 19:03, 4 October 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 = (Bytef*)in; strm.avail_out = 100000; strm.next_out = (Bytef*)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).