gzuncompress
gzuncompress(string $data, int $max_length = 0): string|false
Decompresses bare zlib (RFC 1950) data and returns the original string after Adler32 verification; false on failure.
C C23
#include <stdint.h>
#include <stdio.h>
#include <string.h>
/* Adler-32 (the zlib trailer checksum): mod 65521 */
static uint32_t adler32_of(const uint8_t *p, size_t n) {
uint32_t a = 1, b = 0;
for (size_t i = 0; i < n; i++) {
a = (a + p[i]) % 65521;
b = (b + a) % 65521;
}
return (b << 16) | a;
}
static size_t hex_bytes(const char *hex, uint8_t *out) {
size_t n = strlen(hex) / 2;
for (size_t i = 0; i < n; i++) {
unsigned v;
sscanf(hex + 2 * i, "%2x", &v);
out[i] = (uint8_t)v;
}
return n;
}
/* Hand-written zlib reader (stored blocks only): 11 total overhead = 2 header + 5 block header + 4 trailer; returns 0 on failure */
static size_t zunzlib_store(const uint8_t *in, size_t n, uint8_t *out) {
if (n < 12 || in[0] != 0x78) return 0;
if ((in[2] & 0x06) != 0) return 0; /* BTYPE=00 only */
size_t len = (size_t)in[3] | ((size_t)in[4] << 8);
if (len != n - 11) return 0;
memcpy(out, in + 7, len);
uint32_t a = ((uint32_t)in[7 + len] << 24) | ((uint32_t)in[8 + len] << 16) |
((uint32_t)in[9 + len] << 8) | (uint32_t)in[10 + len];
return a == adler32_of(out, len) ? len : 0;
}
int main(void) {
/* A pre-generated fixed zlib blob (stored-block mode, no timestamp; decompresses identically across platforms) */
const char *zhex = "78010182007dff677a6970207769726520666f726d61743a206d616769632031662038622c206f6e652073746f726564206465666c61746520626c6f636b2c2063726333322b6973697a6520747261696c65722e20677a6970207769726520666f726d61743a206d616769632031662038622c206f6e652073746f726564206465666c61746520626c967e2d27";
uint8_t blob[256], back[512];
size_t bn = hex_bytes(zhex, blob);
size_t dn = zunzlib_store(blob, bn, back);
if (dn == 0) return 1;
back[dn] = 0;
printf("decoded: %s\n", (char *)back);
printf("bytes: %zu\n", dn);
/* Bad data returns 0 (magic or Adler32 check fails) */
printf("bad input: %s\n", zunzlib_store((const uint8_t *)"this is not zlib data", 20, back) == 0 ? "None" : "decoded");
printf("header first byte: %02x\n", blob[0]);
return 0;
}
decoded: gzip wire format: magic 1f 8b, one stored deflate block, crc32+isize trailer. gzip wire format: magic 1f 8b, one stored deflate bl bytes: 130 bad input: None header first byte: 78
C++ C++26
#include <cstdint>
#include <cstdio>
#include <cstring>
#include <iostream>
#include <string>
/* Adler-32 (the zlib trailer checksum): mod 65521 */
static uint32_t adler32_of(const uint8_t *p, size_t n) {
uint32_t a = 1, b = 0;
for (size_t i = 0; i < n; i++) {
a = (a + p[i]) % 65521;
b = (b + a) % 65521;
}
return (b << 16) | a;
}
/* Hand-written zlib reader (stored blocks only): 11 total overhead = 2 header + 5 block header + 4 trailer; returns 0 on failure */
static size_t zunzlib_store(const uint8_t *in, size_t n, std::string &out) {
if (n < 12 || in[0] != 0x78) return 0;
if ((in[2] & 0x06) != 0) return 0; /* BTYPE=00 only */
size_t len = (size_t)in[3] | ((size_t)in[4] << 8);
if (len != n - 11) return 0;
out.assign(reinterpret_cast<const char *>(in) + 7, len);
uint32_t a = ((uint32_t)in[7 + len] << 24) | ((uint32_t)in[8 + len] << 16) |
((uint32_t)in[9 + len] << 8) | (uint32_t)in[10 + len];
return a == adler32_of(reinterpret_cast<const uint8_t *>(out.data()), len) ? len : 0;
}
int main() {
/* A pre-generated fixed zlib blob (stored-block mode, no timestamp; decompresses identically across platforms) */
const char *zhex = "78010182007dff677a6970207769726520666f726d61743a206d616769632031662038622c206f6e652073746f726564206465666c61746520626c6f636b2c2063726333322b6973697a6520747261696c65722e20677a6970207769726520666f726d61743a206d616769632031662038622c206f6e652073746f726564206465666c61746520626c967e2d27";
size_t bn = strlen(zhex) / 2;
std::string zblob(bn, '\0');
for (size_t i = 0; i < bn; i++) {
unsigned v;
sscanf(zhex + 2 * i, "%2x", &v);
zblob[i] = (char)v;
}
std::string back;
size_t dn = zunzlib_store(reinterpret_cast<const uint8_t *>(zblob.data()), zblob.size(), back);
if (dn == 0) return 1;
std::cout << "decoded: " << back << "\n";
std::cout << "bytes: " << dn << "\n";
/* Bad data returns 0 (magic or Adler32 check fails) */
std::cout << "bad input: " << (zunzlib_store(reinterpret_cast<const uint8_t *>("this is not zlib data"), 20, back) == 0 ? "None" : "decoded") << "\n";
std::cout << "header first byte: " << ((zblob[0] == '\x78') ? "78" : "??") << "\n";
return 0;
}
decoded: gzip wire format: magic 1f 8b, one stored deflate block, crc32+isize trailer. gzip wire format: magic 1f 8b, one stored deflate bl bytes: 130 bad input: None header first byte: 78
C# v11.0.100
using System.IO;
using System.IO.Compression;
using System.Text;
// A pre-generated fixed zlib blob (stored-block mode, no timestamp; decompresses identically across platforms)
var zhex = "78010182007dff677a6970207769726520666f726d61743a206d616769632031662038622c206f6e652073746f726564206465666c61746520626c6f636b2c2063726333322b6973697a6520747261696c65722e20677a6970207769726520666f726d61743a206d616769632031662038622c206f6e652073746f726564206465666c61746520626c967e2d27";
var zblob = Convert.FromHexString(zhex);
using var z = new ZLibStream(new MemoryStream(zblob), CompressionMode.Decompress);
using var ms = new MemoryStream();
z.CopyTo(ms);
var text = Encoding.UTF8.GetString(ms.ToArray());
Console.WriteLine($"decoded: {text}");
Console.WriteLine($"bytes: {text.Length}");
// Bad data throws InvalidDataException on first read (wrong magic means rejection)
try
{
using var bad = new ZLibStream(new MemoryStream("this is not zlib data"u8.ToArray()), CompressionMode.Decompress);
bad.CopyTo(new MemoryStream());
}
catch (InvalidDataException)
{
Console.WriteLine("InvalidDataException caught");
}
Console.WriteLine("header first byte: 78");
decoded: gzip wire format: magic 1f 8b, one stored deflate block, crc32+isize trailer. gzip wire format: magic 1f 8b, one stored deflate bl bytes: 130 InvalidDataException caught header first byte: 78
Go v1.27.4
package main
import (
"bytes"
"compress/zlib"
"encoding/hex"
"fmt"
"io"
)
func main() {
// A pre-generated fixed zlib blob (stored-block mode, no timestamp; decompresses identically across platforms)
zhex := "78010182007dff677a6970207769726520666f726d61743a206d616769632031662038622c206f6e652073746f726564206465666c61746520626c6f636b2c2063726333322b6973697a6520747261696c65722e20677a6970207769726520666f726d61743a206d616769632031662038622c206f6e652073746f726564206465666c61746520626c967e2d27"
zblob, _ := hex.DecodeString(zhex)
zr, err := zlib.NewReader(bytes.NewReader(zblob))
if err != nil {
fmt.Println("open failed:", err)
return
}
text, _ := io.ReadAll(zr)
fmt.Println("decoded:", string(text))
fmt.Println("bytes:", len(text))
if err := zr.Close(); err != nil {
fmt.Println("adler check failed:", err)
}
// Bad data reports ErrHeader at NewReader time (wrong magic means rejection)
_, err = zlib.NewReader(bytes.NewReader([]byte("this is not zlib data")))
fmt.Println("bad input:", err)
fmt.Println("header first byte: 78")
}
decoded: gzip wire format: magic 1f 8b, one stored deflate block, crc32+isize trailer. gzip wire format: magic 1f 8b, one stored deflate bl bytes: 130 bad input: zlib: invalid header header first byte: 78
Java v27.0.1
import java.util.zip.Adler32;
import java.util.zip.DataFormatException;
import java.util.zip.Inflater;
public class Main {
static byte[] hexBytes(String s) {
byte[] out = new byte[s.length() / 2];
for (int i = 0; i < out.length; i++) {
out[i] = (byte) Integer.parseInt(s.substring(i * 2, i * 2 + 2), 16);
}
return out;
}
public static void main(String[] args) throws Exception {
// A pre-generated fixed zlib blob (stored-block mode, no timestamp; decompresses identically across platforms)
String zhex = "78010182007dff677a6970207769726520666f726d61743a206d616769632031662038622c206f6e652073746f726564206465666c61746520626c6f636b2c2063726333322b6973697a6520747261696c65722e20677a6970207769726520666f726d61743a206d616769632031662038622c206f6e652073746f726564206465666c61746520626c967e2d27";
byte[] zblob = hexBytes(zhex);
// No zlib wrapper stream in the standard library: hand-rolled unpacking — skip the 2-byte header, Inflater(true) decodes the bare deflate, verify the Adler32 trailer
Inflater inf = new Inflater(true);
inf.setInput(zblob, 2, zblob.length - 6);
byte[] back = new byte[4096];
int n = inf.inflate(back);
inf.end();
System.out.println("decoded: " + new String(back, 0, n));
System.out.println("bytes: " + n);
// Verify the Adler32 (big-endian, the last 4 bytes)
Adler32 ad = new Adler32();
ad.update(back, 0, n);
long expect = ((zblob[zblob.length - 4] & 0xffL) << 24) | ((zblob[zblob.length - 3] & 0xffL) << 16)
| ((zblob[zblob.length - 2] & 0xffL) << 8) | (zblob[zblob.length - 1] & 0xffL);
System.out.println("adler: " + (ad.getValue() == expect ? "ok" : "bad"));
// Bad data throws DataFormatException (an invalid BTYPE means rejection)
try {
Inflater bad = new Inflater(true);
bad.setInput("this is not zlib data".getBytes());
bad.inflate(new byte[64]);
} catch (DataFormatException e) {
System.out.println("DataFormatException caught");
}
System.out.println("header first byte: 78");
}
}
decoded: gzip wire format: magic 1f 8b, one stored deflate block, crc32+isize trailer. gzip wire format: magic 1f 8b, one stored deflate bl bytes: 130 adler: ok DataFormatException caught header first byte: 78
JavaScript v26.13.1
// Node zlib: inflateSync decodes the raw zlib format; bad data throws outright
const zlib = require("node:zlib");
// A pre-generated fixed zlib blob (stored-block mode, no timestamp; decompresses identically across platforms)
const zhex = "78010182007dff677a6970207769726520666f726d61743a206d616769632031662038622c206f6e652073746f726564206465666c61746520626c6f636b2c2063726333322b6973697a6520747261696c65722e20677a6970207769726520666f726d61743a206d616769632031662038622c206f6e652073746f726564206465666c61746520626c967e2d27"
const zblob = Buffer.from(zhex, "hex");
const text = zlib.inflateSync(zblob).toString();
console.log(`decoded: ${text}`);
console.log(`bytes: ${text.length}`);
try {
zlib.inflateSync(Buffer.from("not zlib"));
} catch {
console.log("Error caught");
}
console.log(`header first byte: ${zblob[0].toString(16).padStart(2, "0")}`);
decoded: gzip wire format: magic 1f 8b, one stored deflate block, crc32+isize trailer. gzip wire format: magic 1f 8b, one stored deflate bl bytes: 130 Error caught header first byte: 78
PHP v8.6.0
// gzuncompress: decodes the raw zlib format (RFC 1950); an Adler32 check failure returns false
// A pre-generated fixed zlib blob (stored-block mode, no timestamp; decompresses identically across platforms)
$hex = "78010182007dff677a6970207769726520666f726d61743a206d616769632031662038622c206f6e652073746f726564206465666c61746520626c6f636b2c2063726333322b6973697a6520747261696c65722e20677a6970207769726520666f726d61743a206d616769632031662038622c206f6e652073746f726564206465666c61746520626c967e2d27";
$blob = hex2bin($hex);
$text = gzuncompress($blob);
echo "decoded: ", $text, "\n";
echo "bytes: ", strlen($text), "\n";
// Bad data returns false (wrong magic means rejection; an E_WARNING is raised — validate the header bytes first in production)
var_export(gzuncompress("not zlib"));
echo "\n";
echo "header first byte: ", dechex(ord($blob)), "\n";
decoded: gzip wire format: magic 1f 8b, one stored deflate block, crc32+isize trailer. gzip wire format: magic 1f 8b, one stored deflate bl bytes: 130 false header first byte: 78
Python v3.15.2
import zlib
# A pre-generated fixed zlib blob (stored-block mode, no timestamp; decompresses identically across platforms)
zhex = "78010182007dff677a6970207769726520666f726d61743a206d616769632031662038622c206f6e652073746f726564206465666c61746520626c6f636b2c2063726333322b6973697a6520747261696c65722e20677a6970207769726520666f726d61743a206d616769632031662038622c206f6e652073746f726564206465666c61746520626c967e2d27"
zblob = bytes.fromhex(zhex)
text = zlib.decompress(zblob).decode()
print(f"decoded: {text}")
print(f"bytes: {len(text)}")
# Bad data raises zlib.error (a header or Adler32 check failure means rejection)
try:
zlib.decompress(b"not zlib")
except zlib.error:
print("zlib.error caught")
print(f"header first byte: {zblob[0]:02x}")
decoded: gzip wire format: magic 1f 8b, one stored deflate block, crc32+isize trailer. gzip wire format: magic 1f 8b, one stored deflate bl bytes: 130 zlib.error caught header first byte: 78
Rust v1.99.1
// No compression facilities in Rust's standard library (flate2 crate in real projects):
// A minimal hand-written zlib reader decodes stored-block zlib data (Adler-32 validated)
use std::convert::TryInto;
fn adler32_of(data: &[u8]) -> u32 {
let (mut a, mut b) = (1u32, 0u32);
for &x in data {
a = (a + x as u32) % 65521;
b = (b + a) % 65521;
}
(b << 16) | a
}
fn hex_bytes(s: &str) -> Vec<u8> {
(0..s.len() / 2)
.map(|i| u8::from_str_radix(&s[2 * i..2 * i + 2], 16).unwrap())
.collect()
}
/// Decodes zlib stored blocks: 11 total overhead = 2 header + 5 block header + 4 trailer; returns None on failure
fn zunzlib_store(inp: &[u8]) -> Option<Vec<u8>> {
if inp.len() < 12 || inp[0] != 0x78 || inp[2] & 0x06 != 0 {
return None;
}
let len = u16::from_le_bytes([inp[3], inp[4]]) as usize;
if len != inp.len() - 11 {
return None;
}
let data = &inp[7..7 + len];
let a = u32::from_be_bytes(inp[7 + len..11 + len].try_into().unwrap());
(a == adler32_of(data)).then(|| data.to_vec())
}
fn main() {
// A pre-generated fixed zlib blob (stored-block mode, no timestamp; decompresses identically across platforms)
let zhex = "78010182007dff677a6970207769726520666f726d61743a206d616769632031662038622c206f6e652073746f726564206465666c61746520626c6f636b2c2063726333322b6973697a6520747261696c65722e20677a6970207769726520666f726d61743a206d616769632031662038622c206f6e652073746f726564206465666c61746520626c967e2d27";
let zblob = hex_bytes(zhex);
let text = String::from_utf8(zunzlib_store(&zblob).unwrap()).unwrap();
println!("decoded: {text}");
println!("bytes: {}", zblob.len() - 11);
// Bad data returns None (header or Adler32 check fails)
println!("bad input: {:?}", zunzlib_store(b"this is not zlib data"));
println!("header first byte: {:02x}", zblob[0]);
}
decoded: gzip wire format: magic 1f 8b, one stored deflate block, crc32+isize trailer. gzip wire format: magic 1f 8b, one stored deflate bl bytes: 130 bad input: None header first byte: 78
TypeScript v26.13.1
// Node zlib: inflateSync decodes the raw zlib format; bad data throws outright
import { inflateSync } from "node:zlib";
// A pre-generated fixed zlib blob (stored-block mode, no timestamp; decompresses identically across platforms)
const zhex = "78010182007dff677a6970207769726520666f726d61743a206d616769632031662038622c206f6e652073746f726564206465666c61746520626c6f636b2c2063726333322b6973697a6520747261696c65722e20677a6970207769726520666f726d61743a206d616769632031662038622c206f6e652073746f726564206465666c61746520626c967e2d27"
const zblob = Buffer.from(zhex, "hex");
const text = inflateSync(zblob).toString();
console.log(`decoded: ${text}`);
console.log(`bytes: ${text.length}`);
try {
inflateSync(Buffer.from("not zlib"));
} catch {
console.log("Error caught");
}
console.log(`header first byte: ${zblob[0].toString(16).padStart(2, "0")}`);
decoded: gzip wire format: magic 1f 8b, one stored deflate block, crc32+isize trailer. gzip wire format: magic 1f 8b, one stored deflate bl bytes: 130 Error caught header first byte: 78
Language differences
C: no compression in std — the example hand-writes a zlib reader (stored blocks only, Adler32 verified); real work uses zlib (-lz) via inflateInit (bare zlib is its default windowBits=15).
C++: same as C; boost::iostreams::zlib_decompressor (which defaults to the zlib format).
C#: one ZLibStream(CompressionMode.Decompress) decodes the whole format; corrupt data throws InvalidDataException on first read.
Go: zlib.NewReader validates the header eagerly (bad magic yields ErrHeader); Adler32 is checked on Close.
Java: no zlib wrapper stream in the standard library — Inflater(true) decodes bare deflate while you hand-skip the header and verify the Adler32 trailer (shown); a bad BTYPE throws DataFormatException.
JavaScript: Node zlib.inflateSync; failure semantics are a thrown Error (PHP returns false).
PHP: gzuncompress decodes bare zlib only — it cannot decode gzdecode's gzip format; failure returns false plus an E_WARNING.
Python: zlib.decompress; corrupt data throws zlib.error.
Rust: nothing in std — flate2::read::ZlibDecoder is the idiom; the example hand-writes a stored-blocks-only reader.
TypeScript: same as JavaScript — Node inflateSync.