gzcompress

gzcompress(string $data, int $level = -1, int $max_length = 0): string|false

Compresses a string in bare zlib format (RFC 1950): a 2-byte header, deflate data and an Adler32 trailer — no gzip wrapper.

C C23

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;
}

/* Hand-written zlib writer (stored blocks only, input must be < 65535):
   2-byte header + stored block + big-endian Adler32 tail, 11 bytes of overhead total */
static size_t zlib_store(const uint8_t *in, size_t n, uint8_t *out) {
    size_t o = 0;
    out[o++] = 0x78; out[o++] = 0x01; /* CM=8 deflate, CINFO=7 (32K window), with valid FLG check bits */
    out[o++] = 0x01;                  /* BFINAL=1, BTYPE=00 */
    out[o++] = (uint8_t)(n & 0xff); out[o++] = (uint8_t)(n >> 8);
    out[o++] = (uint8_t)(~n & 0xff); out[o++] = (uint8_t)((~n >> 8) & 0xff);
    memcpy(out + o, in, n); o += n;
    uint32_t a = adler32_of(in, n);
    for (int i = 3; i >= 0; i--) out[o++] = (uint8_t)(a >> (8 * i)); /* Big-endian */
    return o;
}

int main(void) {
    const char *pat = "hello world, ";
    uint8_t raw[260], buf[512];
    size_t rn = 0;
    for (int i = 0; i < 20; i++) {
        memcpy(raw + rn, pat, 13);
        rn += 13;
    }
    printf("raw: %zu\n", rn);
    size_t zn = zlib_store(raw, rn, buf);
    printf("zlib stored (hand-rolled): %zu\n", zn);
    printf("header first byte: %02x\n", buf[0]);
    /* Hand-written reader decodes it back: validates the block length and Adler32 */
    size_t len = (size_t)buf[3] | ((size_t)buf[4] << 8);
    uint32_t a = ((uint32_t)buf[7 + len] << 24) | ((uint32_t)buf[8 + len] << 16) |
                 ((uint32_t)buf[9 + len] << 8) | (uint32_t)buf[10 + len];
    printf("roundtrip: %s\n", len == rn && memcmp(buf + 7, raw, rn) == 0 && a == adler32_of(raw, rn) ? "ok" : "bad");
    return 0;
}
Output
raw: 260
zlib stored (hand-rolled): 271
header first byte: 78
roundtrip: ok

C++ C++26

C++26
#include <cstdint>
#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 writer (stored blocks only): the C++ standard library lacks compression facilities too */
static std::string zlib_store(const std::string &in) {
    std::string out;
    out += (char)0x78; out += (char)0x01; /* CM=8 deflate, 32K window, with valid FLG check bits */
    unsigned short n = (unsigned short)in.size();
    out += (char)0x01;                                         // BFINAL=1, BTYPE=00
    out += (char)(n & 0xff); out += (char)(n >> 8);            // LEN little-endian
    out += (char)(~n & 0xff); out += (char)((~n >> 8) & 0xff); // NLEN
    out += in;
    uint32_t a = adler32_of(reinterpret_cast<const uint8_t *>(in.data()), in.size());
    for (int i = 3; i >= 0; i--) out += (char)((a >> (8 * i)) & 0xff); // Adler32 big-endian
    return out;
}

int main() {
    std::string raw;
    for (int i = 0; i < 20; i++) raw += "hello world, ";
    std::cout << "raw: " << raw.size() << "\n";
    std::string z = zlib_store(raw);
    std::cout << "zlib stored (hand-rolled): " << z.size() << "\n";
    std::cout << "header first byte: " << ((z[0] == '\x78') ? "78" : "??") << "\n";
    /* Hand-written reader decodes it back: validates the block length and Adler32 */
    size_t len = (unsigned char)z[3] | ((size_t)(unsigned char)z[4] << 8);
    bool same = len == raw.size() && z.compare(7, len, raw) == 0;
    uint32_t a = ((uint32_t)(unsigned char)z[7 + len] << 24) | ((uint32_t)(unsigned char)z[8 + len] << 16) |
                 ((uint32_t)(unsigned char)z[9 + len] << 8) | (uint32_t)(unsigned char)z[10 + len];
    std::cout << "roundtrip: " << (same && a == adler32_of(reinterpret_cast<const uint8_t *>(raw.data()), raw.size()) ? "ok" : "bad") << "\n";
    return 0;
}
Output
raw: 260
zlib stored (hand-rolled): 271
header first byte: 78
roundtrip: ok

C# v11.0.100

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

// ZLibStream is the raw zlib format (.NET 6+); DeflateStream is the headerless bare deflate
var raw = Encoding.UTF8.GetBytes(string.Concat(Enumerable.Repeat("hello world, ", 20)));
Console.WriteLine($"raw: {raw.Length}");
var z9 = ZlibWrap(raw, CompressionLevel.Optimal);
Console.WriteLine($"zlib Fastest: {ZlibWrap(raw, CompressionLevel.Fastest).Length}");
Console.WriteLine($"zlib Optimal: {z9.Length}");
Console.WriteLine($"header first byte: {z9[0]:x2}");
Console.WriteLine($"roundtrip: {(ZlibUnwrap(z9).SequenceEqual(raw) ? "ok" : "bad")}");

static byte[] ZlibWrap(byte[] data, CompressionLevel level)
{
    using var ms = new MemoryStream();
    using (var z = new ZLibStream(ms, level, leaveOpen: true)) z.Write(data);
    return ms.ToArray();
}

static byte[] ZlibUnwrap(byte[] zData)
{
    using var z = new ZLibStream(new MemoryStream(zData), CompressionMode.Decompress);
    using var ms = new MemoryStream();
    z.CopyTo(ms);
    return ms.ToArray();
}
Output
raw: 260
zlib Fastest: 23
zlib Optimal: 24
header first byte: 78
roundtrip: ok

Go v1.27.4

v1.27.4
package main

import (
	"bytes"
	"compress/zlib"
	"fmt"
	"io"
)

func main() {
	raw := bytes.Repeat([]byte("hello world, "), 20)
	fmt.Println("raw:", len(raw))
	// compress/zlib: NewWriterLevel picks the level (BestSpeed=1, BestCompression=9); Close appends the Adler32 tail
	var b1, b9 bytes.Buffer
	w1, _ := zlib.NewWriterLevel(&b1, zlib.BestSpeed)
	w1.Write(raw)
	w1.Close()
	w9, _ := zlib.NewWriterLevel(&b9, zlib.BestCompression)
	w9.Write(raw)
	w9.Close()
	fmt.Println("zlib level 1:", b1.Len())
	fmt.Println("zlib level 9:", b9.Len())
	fmt.Printf("header first byte: %02x\n", b9.Bytes()[0])
	zr, _ := zlib.NewReader(bytes.NewReader(b9.Bytes()))
	back, _ := io.ReadAll(zr)
	if string(back) == string(raw) {
		fmt.Println("roundtrip: ok")
	} else {
		fmt.Println("roundtrip: bad")
	}
}
Output
raw: 260
zlib level 1: 24
zlib level 9: 24
header first byte: 78
roundtrip: ok

Java v27.0.1

v27.0.1
import java.io.ByteArrayOutputStream;
import java.util.Arrays;
import java.util.zip.Adler32;
import java.util.zip.Deflater;
import java.util.zip.Inflater;

public class Main {
    // Hand-written zlib packaging: 2-byte header + bare deflate (nowrap=true) + big-endian Adler32 tail
    static byte[] zlibWrap(byte[] raw, int level) {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        out.write(0x78);
        out.write(level > 6 ? 0xDA : (level < 2 ? 0x01 : 0x9C)); // FLG: level bits + check bits
        Deflater def = new Deflater(level, true); // true = bare deflate stream (RFC 1951)
        def.setInput(raw);
        def.finish();
        byte[] buf = new byte[4096];
        while (!def.finished()) {
            int n = def.deflate(buf);
            out.write(buf, 0, n);
        }
        def.end();
        Adler32 ad = new Adler32();
        ad.update(raw);
        long v = ad.getValue();
        for (int i = 3; i >= 0; i--) out.write((int) (v >>> (8 * i)) & 0xff); // Big-endian
        return out.toByteArray();
    }

    public static void main(String[] args) {
        byte[] raw = "hello world, ".repeat(20).getBytes();
        System.out.println("raw: " + raw.length);
        System.out.println("zlib level 1: " + zlibWrap(raw, Deflater.BEST_SPEED).length);
        byte[] z9 = zlibWrap(raw, Deflater.BEST_COMPRESSION);
        System.out.println("zlib level 9: " + z9.length);
        System.out.printf("header first byte: %02x%n", z9[0]);
        // Decoding back: Inflater skips the 2-byte header; the Adler32 tail is outside the stream
        Inflater inf = new Inflater(true);
        inf.setInput(z9, 2, z9.length - 6);
        byte[] back = new byte[4096];
        int n = 0;
        try {
            n = inf.inflate(back);
        } catch (java.util.zip.DataFormatException e) {
            System.out.println("inflate failed");
        }
        inf.end();
        System.out.println("roundtrip: " + (Arrays.equals(back, 0, n, raw, 0, raw.length) ? "ok" : "bad"));
    }
}
Output
raw: 260
zlib level 1: 24
zlib level 9: 24
header first byte: 78
roundtrip: ok

JavaScript v26.13.1

v26.13.1
// Node zlib: deflateSync emits the raw zlib format (inflateSync decodes it back)
const zlib = require("node:zlib");

const raw = Buffer.from("hello world, ".repeat(20));
console.log(`raw: ${raw.length}`);
console.log(`zlib level 1: ${zlib.deflateSync(raw, { level: 1 }).length}`);
const z = zlib.deflateSync(raw, { level: 9 });
console.log(`zlib level 9: ${z.length}`);
console.log(`header first byte: ${z[0].toString(16).padStart(2, "0")}`);
console.log(`roundtrip: ${zlib.inflateSync(z).equals(raw) ? "ok" : "bad"}`);
Output
raw: 260
zlib level 1: 24
zlib level 9: 24
header first byte: 78
roundtrip: ok

PHP v8.6.0

v8.6.0
// gzcompress: the raw zlib format (RFC 1950) = 2-byte header + deflate + Adler32 tail (no gzip header)
$raw = str_repeat("hello world, ", 20);
echo "raw: ", strlen($raw), "\n";
// The level argument matches gzencode (0-9, -1 meaning the default 6); 0 is store mode
echo "zlib level 1: ", strlen(gzcompress($raw, 1)), "\n";
echo "zlib level 9: ", strlen(gzcompress($raw, 9)), "\n";
// The first header byte is CMF=0x78 (CM=8 deflate, 32K window) — different from the gzip magic 1f 8b
echo "header first byte: ", dechex(ord(gzcompress($raw, 9))), "\n";
echo "roundtrip: ", gzuncompress(gzcompress($raw, 9)) === $raw ? "ok" : "bad";
Output
raw: 260
zlib level 1: 24
zlib level 9: 24
header first byte: 78
roundtrip: ok

Python v3.15.2

v3.15.2
import zlib

# zlib.compress: the raw zlib format (RFC 1950); level 0-9 maps to compression levels
raw = b"hello world, " * 20
print(f"raw: {len(raw)}")
print(f"zlib level 1: {len(zlib.compress(raw, 1))}")
print(f"zlib level 9: {len(zlib.compress(raw, 9))}")
z = zlib.compress(raw, 9)
print(f"header first byte: {z[0]:02x}")
print("roundtrip: ok" if zlib.decompress(z) == raw else "roundtrip: bad")
Output
raw: 260
zlib level 1: 24
zlib level 9: 24
header first byte: 78
roundtrip: 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 zlib writer demonstrates the format — stored mode (BTYPE=00) with an Adler-32 checksum
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
}

// Input must be < 65535: 2-byte header + stored block + big-endian Adler32 tail, 11 bytes of overhead total
fn zlib_store(data: &[u8]) -> Vec<u8> {
    let n = data.len();
    let mut out = vec![0x78, 0x01, 0x01]; // CMF/FLG (78 01, valid check bits) + BFINAL=1/BTYPE=00
    out.extend_from_slice(&(n as u16).to_le_bytes());
    out.extend_from_slice(&(!(n as u16)).to_le_bytes()); // NLEN = bitwise complement of LEN
    out.extend_from_slice(data);
    out.extend_from_slice(&adler32_of(data).to_be_bytes());
    out
}

fn main() {
    let raw: Vec<u8> = "hello world, ".repeat(20).into_bytes();
    println!("raw: {}", raw.len());
    let z = zlib_store(&raw);
    println!("zlib stored (hand-rolled): {}", z.len());
    println!("header first byte: {:02x}", z[0]);
    // Hand-written reader decodes it back: validates the block length and Adler32
    let len = u16::from_le_bytes([z[3], z[4]]) as usize;
    let back = &z[7..7 + len];
    let adler = u32::from_be_bytes(z[7 + len..11 + len].try_into().unwrap());
    println!("roundtrip: {}", if len == raw.len() && back == raw.as_slice() && adler32_of(back) == adler { "ok" } else { "bad" });
}
Output
raw: 260
zlib stored (hand-rolled): 271
header first byte: 78
roundtrip: ok

TypeScript v26.13.1

v26.13.1
// Node zlib: deflateSync emits the raw zlib format (inflateSync decodes it back)
import { deflateSync, inflateSync } from "node:zlib";

const raw = Buffer.from("hello world, ".repeat(20));
console.log(`raw: ${raw.length}`);
console.log(`zlib level 1: ${deflateSync(raw, { level: 1 }).length}`);
const z = deflateSync(raw, { level: 9 });
console.log(`zlib level 9: ${z.length}`);
console.log(`header first byte: ${z[0].toString(16).padStart(2, "0")}`);
console.log(`roundtrip: ${inflateSync(z).equals(raw) ? "ok" : "bad"}`);
Output
raw: 260
zlib level 1: 24
zlib level 9: 24
header first byte: 78
roundtrip: ok

Language differences

C: no compression in std — the example hand-writes the zlib framing (stored mode + Adler32); real deflate needs third-party zlib (-lz, whose compress/compress2 is this function's twin).

C++: same as C; real work uses zlib (-lz) or boost::iostreams.

C#: ZLibStream (.NET 6+) is the bare zlib format; DeflateStream is the header-less raw deflate — the three (GZip/ZLib/Deflate) differ only by header and trailer; .NET's Fastest differs from zlib level 1 in strategy (23 vs 24 here).

Go: compress/zlib with zlib.NewWriterLevel for the level; the writer must Close to flush the Adler32 trailer.

Java: a default Deflater (nowrap=false) emits the zlib wrapper already but at a fixed level; to control it, hand-wrap Deflater(level, true) with header and trailer (shown, including FLEVEL semantics: 78 01 / 78 9C / 78 DA).

JavaScript: Node's zlib.deflateSync is the bare zlib format; deflateRawSync is the header-less raw deflate; inflateSync decodes.

PHP: gzcompress differs from gzencode by one header and one trailer — zlib's 2-byte header + 4-byte Adler32 vs gzip's 10-byte header + 8-byte CRC32/ISIZE; use gzencode for network/file compression, gzcompress for tight embedding; gzuncompress decodes, and the two are not interchangeable.

Python: zlib.compress(data, level); decode with zlib.decompress; gzip.compress is zlib.compress plus the header/trailer wrap.

Rust: nothing in std — flate2's ZlibEncoder is the equivalent; the example hand-writes stored mode to show the format.

TypeScript: same as JavaScript.