gzencode

gzencode(string $data, int $level = -1, int $encoding = FORCE_GZIP): string|false

Compresses a string in gzip format (RFC 1952); level 0-9 controls compression (0 = stored, no compression).

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

/* Hand-written gzip writer (stored blocks only, input must be < 65535):
   10-byte header + stored block + CRC32/ISIZE tail, 23 bytes of overhead total */
static size_t gzip_store(const uint8_t *in, size_t n, uint8_t *out) {
    size_t o = 0;
    out[o++] = 0x1f; out[o++] = 0x8b; out[o++] = 8; out[o++] = 0; /* magic + CM=deflate */
    memset(out + o, 0, 4); o += 4;                                /* MTIME=0 (deterministic) */
    out[o++] = 0; out[o++] = 3;                                   /* XFL、OS=Unix */
    out[o++] = 0x01;                                              /* BFINAL=1, BTYPE=00 */
    out[o++] = (uint8_t)(n & 0xff); out[o++] = (uint8_t)(n >> 8); /* LEN little-endian */
    out[o++] = (uint8_t)(~n & 0xff); out[o++] = (uint8_t)((~n >> 8) & 0xff); /* NLEN */
    memcpy(out + o, in, n); o += n;
    uint32_t c = crc32_of(in, n);
    memcpy(out + o, &c, 4); o += 4;                               /* CRC32 little-endian */
    uint32_t s = (uint32_t)n;
    memcpy(out + o, &s, 4); o += 4;                               /* ISIZE little-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 gn = gzip_store(raw, rn, buf);
    printf("gzip stored (hand-rolled): %zu\n", gn);
    printf("gzip magic: %s\n", buf[0] == 0x1f && buf[1] == 0x8b ? "ok" : "bad");
    /* Hand-written reader decodes it back: validates the block length and CRC32 */
    size_t len = (size_t)buf[11] | ((size_t)buf[12] << 8);
    printf("roundtrip: %s\n", len == rn && crc32_of(buf + 15, len) == crc32_of(raw, rn) ? "ok" : "bad");
    return 0;
}
Output
raw: 260
gzip stored (hand-rolled): 283
gzip magic: ok
roundtrip: ok

C++ C++26

C++26
#include <cstdint>
#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 writer (stored blocks only): the C++ standard library lacks compression facilities too */
static std::string gzip_store(const std::string &in) {
    std::string out;
    const unsigned char head[10] = {0x1f, 0x8b, 0x08, 0, 0, 0, 0, 0, 0, 0x03};
    out.append(reinterpret_cast<const char *>(head), 10); // magic + CM + MTIME=0 + OS
    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 c = crc32_of(reinterpret_cast<const uint8_t *>(in.data()), in.size());
    for (int i = 0; i < 4; i++) out += (char)((c >> (8 * i)) & 0xff); // CRC32 little-endian
    uint32_t s = (uint32_t)in.size();
    for (int i = 0; i < 4; i++) out += (char)((s >> (8 * i)) & 0xff); // ISIZE little-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 g = gzip_store(raw);
    std::cout << "gzip stored (hand-rolled): " << g.size() << "\n";
    std::cout << "gzip magic: " << ((g[0] == '\x1f' && g[1] == '\x8b') ? "ok" : "bad") << "\n";
    /* Hand-written reader decodes it back: validates the block length and CRC32 */
    size_t len = (unsigned char)g[11] | ((size_t)(unsigned char)g[12] << 8);
    bool same = len == raw.size() && g.compare(15, len, raw) == 0;
    std::cout << "roundtrip: " << (same && crc32_of(reinterpret_cast<const uint8_t *>(g.data()) + 15, len) == crc32_of(reinterpret_cast<const uint8_t *>(raw.data()), raw.size()) ? "ok" : "bad") << "\n";
    return 0;
}
Output
raw: 260
gzip stored (hand-rolled): 283
gzip magic: ok
roundtrip: ok

C# v11.0.100

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

// GZipStream compresses in the full gzip format; CompressionLevel picks the level (Fastest≈1, Optimal≈9)
var raw = Encoding.UTF8.GetBytes(string.Concat(Enumerable.Repeat("hello world, ", 20)));
Console.WriteLine($"raw: {raw.Length}");
var g9 = GzipWrap(raw, CompressionLevel.Optimal);
Console.WriteLine($"gzip Fastest: {GzipWrap(raw, CompressionLevel.Fastest).Length}");
Console.WriteLine($"gzip Optimal: {g9.Length}");
Console.WriteLine($"gzip magic: {(g9[0] == 0x1f && g9[1] == 0x8b ? "ok" : "bad")}");
Console.WriteLine($"roundtrip: {(GzipUnwrap(g9).SequenceEqual(raw) ? "ok" : "bad")}");

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

static byte[] GzipUnwrap(byte[] gzData)
{
    using var gz = new GZipStream(new MemoryStream(gzData), CompressionMode.Decompress);
    using var ms = new MemoryStream();
    gz.CopyTo(ms);
    return ms.ToArray();
}
Output
raw: 260
gzip Fastest: 35
gzip Optimal: 36
gzip magic: ok
roundtrip: ok

Go v1.27.4

v1.27.4
package main

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

func main() {
	raw := bytes.Repeat([]byte("hello world, "), 20)
	fmt.Println("raw:", len(raw))
	// NewWriterLevel picks the compression level (BestSpeed=1, BestCompression=9); you must Close after writing to append the trailer
	var b1, b9 bytes.Buffer
	w1, _ := gzip.NewWriterLevel(&b1, gzip.BestSpeed)
	w1.Write(raw)
	w1.Close()
	w9, _ := gzip.NewWriterLevel(&b9, gzip.BestCompression)
	w9.Write(raw)
	w9.Close()
	fmt.Println("gzip level 1:", b1.Len())
	fmt.Println("gzip level 9:", b9.Len())
	fmt.Println("gzip magic: ok")
	r, _ := gzip.NewReader(bytes.NewReader(b9.Bytes()))
	back, _ := io.ReadAll(r)
	if string(back) == string(raw) {
		fmt.Println("roundtrip: ok")
	} else {
		fmt.Println("roundtrip: bad")
	}
}
Output
raw: 260
gzip level 1: 36
gzip level 9: 36
gzip magic: ok
roundtrip: ok

Java v27.0.1

v27.0.1
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.util.Arrays;
import java.util.zip.CRC32;
import java.util.zip.Deflater;
import java.util.zip.GZIPInputStream;

public class Main {
    // Hand-written gzip packaging: 10-byte header + bare deflate + CRC32/ISIZE tail
    // GZIPOutputStream cannot pick a compression level; Deflater(level, true) is the level-controllable path
    static byte[] gzipWrap(byte[] raw, int level) throws Exception {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        out.writeBytes(new byte[]{(byte) 0x1f, (byte) 0x8b, 8, 0, 0, 0, 0, 0, 0, 3});
        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();
        CRC32 crc = new CRC32();
        crc.update(raw);
        long v = crc.getValue();
        for (int i = 0; i < 4; i++) out.write((int) (v >>> (8 * i)) & 0xff); // CRC32 little-endian
        for (int i = 0; i < 4; i++) out.write((int) ((long) raw.length >>> (8 * i)) & 0xff); // ISIZE little-endian
        return out.toByteArray();
    }

    public static void main(String[] args) throws Exception {
        byte[] raw = "hello world, ".repeat(20).getBytes();
        System.out.println("raw: " + raw.length);
        System.out.println("gzip level 1: " + gzipWrap(raw, Deflater.BEST_SPEED).length);
        byte[] g9 = gzipWrap(raw, Deflater.BEST_COMPRESSION);
        System.out.println("gzip level 9: " + g9.length);
        System.out.println("gzip magic: " + (g9[0] == 0x1f && g9[1] == (byte) 0x8b ? "ok" : "bad"));
        // Decode back with GZIPInputStream: proving the hand-rolled packaging is valid gzip
        byte[] back = new GZIPInputStream(new ByteArrayInputStream(g9)).readAllBytes();
        System.out.println("roundtrip: " + (Arrays.equals(back, raw) ? "ok" : "bad"));
    }
}
Output
raw: 260
gzip level 1: 36
gzip level 9: 36
gzip magic: ok
roundtrip: ok

JavaScript v26.13.1

v26.13.1
// Node zlib: gzipSync compresses in the gzip format; level 0-9 maps to compression levels
const zlib = require("node:zlib");

const raw = Buffer.from("hello world, ".repeat(20));
console.log(`raw: ${raw.length}`);
console.log(`gzip level 1: ${zlib.gzipSync(raw, { level: 1 }).length}`);
console.log(`gzip level 9: ${zlib.gzipSync(raw, { level: 9 }).length}`);
console.log("gzip magic: ok");
console.log(`roundtrip: ${zlib.gunzipSync(zlib.gzipSync(raw, { level: 9 })).equals(raw) ? "ok" : "bad"}`);
Output
raw: 260
gzip level 1: 36
gzip level 9: 36
gzip magic: ok
roundtrip: ok

PHP v8.6.0

v8.6.0
// gzencode: the gzip format (RFC 1952) = 10-byte header + deflate data + CRC32/ISIZE tail
$raw = str_repeat("hello world, ", 20);
echo "raw: ", strlen($raw), "\n";
// The 2nd argument level: 0 no compression (store mode), -1 the default (6), 9 the best ratio
echo "gzip level 1: ", strlen(gzencode($raw, 1)), "\n";
echo "gzip level 9: ", strlen(gzencode($raw, 9)), "\n";
// The output is binary: it starts with the gzip magic 1f 8b
echo "gzip magic: ", substr(gzencode($raw, 9), 0, 2) === "\x1f\x8b" ? "ok" : "bad", "\n";
echo "roundtrip: ", gzdecode(gzencode($raw, 9)) === $raw ? "ok" : "bad";
Output
raw: 260
gzip level 1: 36
gzip level 9: 36
gzip magic: ok
roundtrip: ok

Python v3.15.2

v3.15.2
import gzip

# gzip.compress: the gzip format (RFC 1952); level 0-9 maps to compression levels, 0 is store mode
raw = b"hello world, " * 20
print(f"raw: {len(raw)}")
print(f"gzip level 1: {len(gzip.compress(raw, 1))}")
print(f"gzip level 9: {len(gzip.compress(raw, 9))}")
print("gzip magic: ok" if gzip.compress(raw, 9)[:2] == b"\x1f\x8b" else "gzip magic: bad")
print("roundtrip: ok" if gzip.decompress(gzip.compress(raw, 9)) == raw else "roundtrip: bad")
Output
raw: 260
gzip level 1: 36
gzip level 9: 36
gzip magic: ok
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 gzip writer demonstrates the format — stored mode (BTYPE=00) with a CRC-32 checksum
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
}

// Input must be < 65535: 10-byte header + stored block (LEN/NLEN little-endian) + CRC32/ISIZE tail, 23 bytes of overhead total
fn gzip_store(data: &[u8]) -> Vec<u8> {
    let n = data.len();
    let mut out = vec![0x1f, 0x8b, 8, 0, 0, 0, 0, 0, 0, 3]; // magic + CM=deflate + MTIME=0 + OS=Unix
    out.push(0x01); // BFINAL=1, BTYPE=00 stored
    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(&crc32_of(data).to_le_bytes());
    out.extend_from_slice(&(n as u32).to_le_bytes());
    out
}

fn main() {
    let raw: Vec<u8> = "hello world, ".repeat(20).into_bytes();
    println!("raw: {}", raw.len());
    let g = gzip_store(&raw);
    println!("gzip stored (hand-rolled): {}", g.len());
    println!("gzip magic: {}", if g[0] == 0x1f && g[1] == 0x8b { "ok" } else { "bad" });
    // Hand-written reader decodes it back: validates the block length and CRC32
    let len = u16::from_le_bytes([g[11], g[12]]) as usize;
    let back = &g[15..15 + len];
    println!("roundtrip: {}", if len == raw.len() && back == raw.as_slice() && crc32_of(back) == crc32_of(&raw) { "ok" } else { "bad" });
}
Output
raw: 260
gzip stored (hand-rolled): 283
gzip magic: ok
roundtrip: ok

TypeScript v26.13.1

v26.13.1
// Node zlib: gzipSync compresses in the gzip format; level 0-9 maps to compression levels
import { gzipSync, gunzipSync } from "node:zlib";

const raw = Buffer.from("hello world, ".repeat(20));
console.log(`raw: ${raw.length}`);
console.log(`gzip level 1: ${gzipSync(raw, { level: 1 }).length}`);
console.log(`gzip level 9: ${gzipSync(raw, { level: 9 }).length}`);
console.log("gzip magic: ok");
console.log(`roundtrip: ${gunzipSync(gzipSync(raw, { level: 9 })).equals(raw) ? "ok" : "bad"}`);
Output
raw: 260
gzip level 1: 36
gzip level 9: 36
gzip magic: ok
roundtrip: ok

Language differences

C: no compression in the standard library — the example hand-writes gzip stored mode (10-byte header + stored block + CRC32/ISIZE trailer); real deflate needs third-party zlib (-lz).

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

C#: GZipStream emits full gzip format; CompressionLevel.Fastest/Optimal map to levels 1/9 — but .NET's Fastest strategy differs from zlib and comes out slightly larger on repetitive text (35 vs 36 here); Optimal matches level 9.

Go: compress/gzip with gzip.NewWriterLevel to pick the level; the writer must be Closed to flush the CRC32/ISIZE trailer.

Java: GZIPOutputStream is fixed at the default level; to control it, hand-wrap a Deflater(level, true) (bare deflate) with the header and trailer (shown).

JavaScript: Node ships zlib.gzipSync(data, { level }) plus the async variants; gunzipSync to decode.

PHP: gzencode emits full gzip (RFC 1952) — differing from gzcompress's bare zlib format by one header and trailer: gzip adds a 10-byte header (magic 1f 8b / MTIME / OS) and an 8-byte CRC32/ISIZE trailer; gzdecode decodes it.

Python: gzip.compress(data, level); decode with gzip.decompress.

Rust: nothing in std — flate2 is the de-facto crate; the example hand-writes stored mode to show the format.

TypeScript: same as JavaScript — the full Node zlib gzip API.