gzdecode

gzdecode(string $data, int $max_length = 0): string|false

Decompresses gzip (RFC 1952) data and returns the original string after CRC32 verification; false on failure.

C C23

C23
#include <stdint.h>
#include <stdio.h>
#include <string.h>

/* CRC-32 (IEEE, the gzip trailer checksum): bitwise method, no lookup table */
static uint32_t crc32_of(const uint8_t *p, size_t n) {
    uint32_t c = 0xFFFFFFFFu;
    for (size_t i = 0; i < n; i++) {
        c ^= p[i];
        for (int k = 0; k < 8; k++) {
            c = (c >> 1) ^ (0xEDB88320u & (uint32_t)-(int32_t)(c & 1));
        }
    }
    return c ^ 0xFFFFFFFFu;
}

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 gzip reader (stored blocks only): 23 total overhead = 10 header + 5 block header + 8 trailer; returns 0 on failure */
static size_t gunzip_store(const uint8_t *in, size_t n, uint8_t *out) {
    if (n < 23 || in[0] != 0x1f || in[1] != 0x8b || in[2] != 8) return 0;
    if ((in[10] & 0x06) != 0) return 0;                    /* BTYPE=00 only */
    size_t len = (size_t)in[11] | ((size_t)in[12] << 8);
    if (len != n - 23) return 0;
    memcpy(out, in + 15, len);
    uint32_t c;
    memcpy(&c, in + 15 + len, 4);
    return c == crc32_of(out, len) ? len : 0;
}

int main(void) {
    /* A pre-generated fixed gzip blob (stored-block mode, mtime=0; decompresses identically across platforms) */
    const char *gzhex = "1f8b08000000000004ff0182007dff677a6970207769726520666f726d61743a206d616769632031662038622c206f6e652073746f726564206465666c61746520626c6f636b2c2063726333322b6973697a6520747261696c65722e20677a6970207769726520666f726d61743a206d616769632031662038622c206f6e652073746f726564206465666c61746520626ca9889ce382000000";
    uint8_t blob[256], back[512];
    size_t bn = hex_bytes(gzhex, blob);
    size_t dn = gunzip_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 CRC check fails) */
    printf("bad input: %s\n", gunzip_store((const uint8_t *)"not gzip", 8, back) == 0 ? "None" : "decoded");
    printf("gzip magic: %s\n", blob[0] == 0x1f && blob[1] == 0x8b ? "ok" : "bad");
    return 0;
}
Output
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
gzip magic: ok

C++ C++26

C++26
#include <cstdint>
#include <cstdio>
#include <cstring>
#include <iostream>
#include <string>

/* CRC-32 (IEEE, the gzip trailer checksum): bitwise method, no lookup table */
static uint32_t crc32_of(const uint8_t *p, size_t n) {
    uint32_t c = 0xFFFFFFFFu;
    for (size_t i = 0; i < n; i++) {
        c ^= p[i];
        for (int k = 0; k < 8; k++) {
            c = (c >> 1) ^ (0xEDB88320u & (uint32_t)-(int32_t)(c & 1));
        }
    }
    return c ^ 0xFFFFFFFFu;
}

/* Hand-written gzip reader (stored blocks only): 23 total overhead = 10 header + 5 block header + 8 trailer; returns 0 on failure */
static size_t gunzip_store(const uint8_t *in, size_t n, std::string &out) {
    if (n < 23 || in[0] != 0x1f || in[1] != 0x8b || in[2] != 8) return 0;
    if ((in[10] & 0x06) != 0) return 0;                    /* BTYPE=00 only */
    size_t len = (size_t)in[11] | ((size_t)in[12] << 8);
    if (len != n - 23) return 0;
    out.assign(reinterpret_cast<const char *>(in) + 15, len);
    uint32_t c;
    memcpy(&c, in + 15 + len, 4);
    return c == crc32_of(reinterpret_cast<const uint8_t *>(out.data()), len) ? len : 0;
}

int main() {
    /* A pre-generated fixed gzip blob (stored-block mode, mtime=0; decompresses identically across platforms) */
    const char *gzhex = "1f8b08000000000004ff0182007dff677a6970207769726520666f726d61743a206d616769632031662038622c206f6e652073746f726564206465666c61746520626c6f636b2c2063726333322b6973697a6520747261696c65722e20677a6970207769726520666f726d61743a206d616769632031662038622c206f6e652073746f726564206465666c61746520626ca9889ce382000000";
    size_t bn = strlen(gzhex) / 2;
    std::string blob(bn, '\0');
    for (size_t i = 0; i < bn; i++) {
        unsigned v;
        sscanf(gzhex + 2 * i, "%2x", &v);
        blob[i] = (char)v;
    }
    std::string back;
    size_t dn = gunzip_store(reinterpret_cast<const uint8_t *>(blob.data()), blob.size(), back);
    if (dn == 0) return 1;
    std::cout << "decoded: " << back << "\n";
    std::cout << "bytes: " << dn << "\n";
    /* Bad data returns 0 (magic or CRC check fails) */
    std::cout << "bad input: " << (gunzip_store(reinterpret_cast<const uint8_t *>("not gzip"), 8, back) == 0 ? "None" : "decoded") << "\n";
    std::cout << "gzip magic: " << ((blob[0] == '\x1f' && blob[1] == '\x8b') ? "ok" : "bad") << "\n";
    return 0;
}
Output
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
gzip magic: ok

C# v11.0.100

v11.0.100
using System.IO;
using System.IO.Compression;
using System.Text;

// A pre-generated fixed gzip blob (stored-block mode, mtime=0; decompresses identically across platforms)
var gzhex = "1f8b08000000000004ff0182007dff677a6970207769726520666f726d61743a206d616769632031662038622c206f6e652073746f726564206465666c61746520626c6f636b2c2063726333322b6973697a6520747261696c65722e20677a6970207769726520666f726d61743a206d616769632031662038622c206f6e652073746f726564206465666c61746520626ca9889ce382000000";
var blob = Convert.FromHexString(gzhex);
using var gz = new GZipStream(new MemoryStream(blob), CompressionMode.Decompress);
using var ms = new MemoryStream();
gz.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 GZipStream(new MemoryStream("not gzip"u8.ToArray()), CompressionMode.Decompress);
    bad.CopyTo(new MemoryStream());
}
catch (InvalidDataException)
{
    Console.WriteLine("InvalidDataException caught");
}
Console.WriteLine("gzip magic: ok");
Output
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
gzip magic: ok

Go v1.27.4

v1.27.4
package main

import (
	"bytes"
	"compress/gzip"
	"encoding/hex"
	"fmt"
	"io"
)

func main() {
	// A pre-generated fixed gzip blob (stored-block mode, mtime=0; decompresses identically across platforms)
	gzhex := "1f8b08000000000004ff0182007dff677a6970207769726520666f726d61743a206d616769632031662038622c206f6e652073746f726564206465666c61746520626c6f636b2c2063726333322b6973697a6520747261696c65722e20677a6970207769726520666f726d61743a206d616769632031662038622c206f6e652073746f726564206465666c61746520626ca9889ce382000000"
	blob, _ := hex.DecodeString(gzhex)
	r, err := gzip.NewReader(bytes.NewReader(blob))
	if err != nil {
		fmt.Println("open failed:", err)
		return
	}
	text, _ := io.ReadAll(r)
	fmt.Println("decoded:", string(text))
	fmt.Println("bytes:", len(text))
	// Bad data reports ErrHeader at NewReader time (wrong magic means rejection)
	_, err = gzip.NewReader(bytes.NewReader([]byte("this is not gzip data")))
	fmt.Println("bad input:", err)
	fmt.Println("gzip magic: ok")
}
Output
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: gzip: invalid header
gzip magic: ok

Java v27.0.1

v27.0.1
import java.io.ByteArrayInputStream;
import java.util.zip.GZIPInputStream;
import java.util.zip.ZipException;

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 gzip blob (stored-block mode, mtime=0; decompresses identically across platforms)
        String gzhex = "1f8b08000000000004ff0182007dff677a6970207769726520666f726d61743a206d616769632031662038622c206f6e652073746f726564206465666c61746520626c6f636b2c2063726333322b6973697a6520747261696c65722e20677a6970207769726520666f726d61743a206d616769632031662038622c206f6e652073746f726564206465666c61746520626ca9889ce382000000";
        byte[] blob = hexBytes(gzhex);
        byte[] back = new GZIPInputStream(new ByteArrayInputStream(blob)).readAllBytes();
        System.out.println("decoded: " + new String(back));
        System.out.println("bytes: " + back.length);
        // Bad data throws ZipException when the stream is constructed (wrong magic means rejection)
        try {
            new GZIPInputStream(new ByteArrayInputStream("not gzip".getBytes()));
        } catch (ZipException e) {
            System.out.println("ZipException caught");
        }
        System.out.println("gzip magic: ok");
    }
}
Output
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
ZipException caught
gzip magic: ok

JavaScript v26.13.1

v26.13.1
// Node zlib: gunzipSync decodes gzip; bad data throws outright
const zlib = require("node:zlib");

// A pre-generated fixed gzip blob (stored-block mode, mtime=0; decompresses identically across platforms)
const gzhex = "1f8b08000000000004ff0182007dff677a6970207769726520666f726d61743a206d616769632031662038622c206f6e652073746f726564206465666c61746520626c6f636b2c2063726333322b6973697a6520747261696c65722e20677a6970207769726520666f726d61743a206d616769632031662038622c206f6e652073746f726564206465666c61746520626ca9889ce382000000";
const blob = Buffer.from(gzhex, "hex");
const text = zlib.gunzipSync(blob).toString();
console.log(`decoded: ${text}`);
console.log(`bytes: ${text.length}`);
try {
  zlib.gunzipSync(Buffer.from("not gzip"));
} catch {
  console.log("Error caught");
}
console.log("gzip magic: ok");
Output
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
gzip magic: ok

PHP v8.6.0

v8.6.0
// gzdecode: decodes the gzip format (RFC 1952); a CRC32 check failure returns false
// Below is a pre-generated fixed gzip blob (stored-block mode, MTIME=0; decompresses identically across platforms)
$hex = "1f8b08000000000004ff0182007dff677a6970207769726520666f726d61743a206d616769632031662038622c206f6e652073746f726564206465666c61746520626c6f636b2c2063726333322b6973697a6520747261696c65722e20677a6970207769726520666f726d61743a206d616769632031662038622c206f6e652073746f726564206465666c61746520626ca9889ce382000000";
$blob = hex2bin($hex);
$text = gzdecode($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 magic first in production)
var_export(gzdecode("not gzip"));
echo "\n";
echo "gzip magic: ", substr($blob, 0, 2) === "\x1f\x8b" ? "ok" : "bad";
Output
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
gzip magic: ok

Python v3.15.2

v3.15.2
import gzip

# A pre-generated fixed gzip blob (stored-block mode, mtime=0; decompresses identically across platforms)
gzhex = "1f8b08000000000004ff0182007dff677a6970207769726520666f726d61743a206d616769632031662038622c206f6e652073746f726564206465666c61746520626c6f636b2c2063726333322b6973697a6520747261696c65722e20677a6970207769726520666f726d61743a206d616769632031662038622c206f6e652073746f726564206465666c61746520626ca9889ce382000000"
blob = bytes.fromhex(gzhex)
text = gzip.decompress(blob).decode()
print(f"decoded: {text}")
print(f"bytes: {len(text)}")
# Bad data raises BadGzipFile (wrong magic means rejection)
try:
    gzip.decompress(b"not gzip")
except gzip.BadGzipFile:
    print("BadGzipFile caught")
print("gzip magic: ok" if blob[:2] == b"\x1f\x8b" else "gzip magic: bad")
Output
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
BadGzipFile caught
gzip magic: ok

Rust v1.99.1

v1.99.1
// No compression facilities in Rust's standard library (flate2 crate in real projects):
// A minimal hand-written gzip reader decodes stored-block gzip data (CRC-32 validated)
use std::convert::TryInto;

fn crc32_of(data: &[u8]) -> u32 {
    let mut c: u32 = 0xFFFF_FFFF;
    for &b in data {
        c ^= b as u32;
        for _ in 0..8 {
            c = if c & 1 == 1 { (c >> 1) ^ 0xEDB8_8320 } else { c >> 1 };
        }
    }
    !c
}

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 gzip stored blocks: 23 total overhead = 10 header + 5 block header + 8 trailer; returns None on failure
fn gunzip_store(inp: &[u8]) -> Option<Vec<u8>> {
    if inp.len() < 23 || inp[0] != 0x1f || inp[1] != 0x8b || inp[2] != 8 {
        return None;
    }
    if inp[10] & 0x06 != 0 {
        return None; // BTYPE=00 only
    }
    let len = u16::from_le_bytes([inp[11], inp[12]]) as usize;
    if len != inp.len() - 23 {
        return None;
    }
    let data = &inp[15..15 + len];
    let crc = u32::from_le_bytes(inp[15 + len..19 + len].try_into().unwrap());
    (crc == crc32_of(data)).then(|| data.to_vec())
}

fn main() {
    // A pre-generated fixed gzip blob (stored-block mode, mtime=0; decompresses identically across platforms)
    let gzhex = "1f8b08000000000004ff0182007dff677a6970207769726520666f726d61743a206d616769632031662038622c206f6e652073746f726564206465666c61746520626c6f636b2c2063726333322b6973697a6520747261696c65722e20677a6970207769726520666f726d61743a206d616769632031662038622c206f6e652073746f726564206465666c61746520626ca9889ce382000000";
    let blob = hex_bytes(gzhex);
    let text = String::from_utf8(gunzip_store(&blob).unwrap()).unwrap();
    println!("decoded: {text}");
    println!("bytes: {}", blob.len() - 23);
    // Bad data returns None (magic or CRC check fails)
    println!("bad input: {:?}", gunzip_store(b"not gzip"));
    println!("gzip magic: {}", if blob[0] == 0x1f && blob[1] == 0x8b { "ok" } else { "bad" });
}
Output
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
gzip magic: ok

TypeScript v26.13.1

v26.13.1
// Node zlib: gunzipSync decodes gzip; bad data throws outright
import { gunzipSync } from "node:zlib";

// A pre-generated fixed gzip blob (stored-block mode, mtime=0; decompresses identically across platforms)
const gzhex = "1f8b08000000000004ff0182007dff677a6970207769726520666f726d61743a206d616769632031662038622c206f6e652073746f726564206465666c61746520626c6f636b2c2063726333322b6973697a6520747261696c65722e20677a6970207769726520666f726d61743a206d616769632031662038622c206f6e652073746f726564206465666c61746520626ca9889ce382000000";
const blob = Buffer.from(gzhex, "hex");
const text = gunzipSync(blob).toString();
console.log(`decoded: ${text}`);
console.log(`bytes: ${text.length}`);
try {
  gunzipSync(Buffer.from("not gzip"));
} catch {
  console.log("Error caught");
}
console.log("gzip magic: ok");
Output
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
gzip magic: ok

Language differences

C: no compression in std — the example hand-writes a gzip reader (stored blocks only, CRC32 verified); real work uses zlib (-lz) via inflateInit2 with windowBits=31.

C++: same as C; boost::iostreams::gzip_decompressor or minizip.

C#: one GZipStream(CompressionMode.Decompress) decodes the whole format; corrupt data throws InvalidDataException on first read.

Go: gzip.NewReader validates the header eagerly (bad magic yields ErrHeader); the trailer CRC32 is checked on Close.

Java: GZIPInputStream checks the magic in its constructor (ZipException on bad data) and verifies CRC32 at end of stream.

JavaScript: Node zlib.gunzipSync; failure semantics are a thrown Error (PHP returns false).

PHP: gzdecode decodes gzip only — it cannot decode gzcompress's bare zlib format; failure returns false plus an E_WARNING.

Python: gzip.decompress; corrupt data throws gzip.BadGzipFile.

Rust: nothing in std — flate2::read::GzDecoder is the idiom; the example hand-writes a stored-blocks-only reader.

TypeScript: same as JavaScript — Node gunzipSync.