gzuncompress
gzuncompress(string $data, int $max_length = 0): string|false
解压 zlib 裸格式(RFC 1950)数据,校验 Adler32 后返回原始字符串,失败返回 false。
C C23
C23
#include <stdint.h>
#include <stdio.h>
#include <string.h>
/* Adler-32(zlib 尾部校验):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;
}
/* 手写 zlib 读取器(只解存储块):总开销 11 = 2 头 + 5 块头 + 4 尾,失败返回 0 */
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 */
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) {
/* 预生成的固定 zlib blob(存储块模式、无时间戳,跨平台解压结果一致) */
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);
/* 坏数据返回 0(魔数或 Adler32 校验不过)——C 用返回值表意 */
printf("bad input: %s\n", zunzlib_store((const uint8_t *)"this is not zlib data", 20, back) == 0 ? "None" : "decoded");
/* 解压前可先看头字节:78 是 zlib 裸格式的身份证(gzip 是 1f 8b) */
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
C++26
#include <cstdint>
#include <cstdio>
#include <cstring>
#include <iostream>
#include <string>
/* Adler-32(zlib 尾部校验):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;
}
/* 手写 zlib 读取器(只解存储块):总开销 11 = 2 头 + 5 块头 + 4 尾,失败返回 0 */
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 */
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() {
/* 预生成的固定 zlib blob(存储块模式、无时间戳,跨平台解压结果一致) */
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";
/* 坏数据返回 0(魔数或 Adler32 校验不过)——C++ 同 C 用返回值表意 */
std::cout << "bad input: " << (zunzlib_store(reinterpret_cast<const uint8_t *>("this is not zlib data"), 20, back) == 0 ? "None" : "decoded") << "\n";
/* 解压前可先看头字节:78 是 zlib 裸格式的身份证(gzip 是 1f 8b) */
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
v11.0.100
using System.IO;
using System.IO.Compression;
using System.Text;
// 预生成的固定 zlib blob(存储块模式、无时间戳,跨平台解压结果一致)
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}");
// 坏数据在首次读取时抛 InvalidDataException(魔数不对即拒收)——C# 用异常而非 false
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");
}
// 解压前可先看头字节:78 是 zlib 裸格式的身份证(gzip 是 1f 8b)
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
v1.27.4
package main
import (
"bytes"
"compress/zlib"
"encoding/hex"
"fmt"
"io"
)
func main() {
// 预生成的固定 zlib blob(存储块模式、无时间戳,跨平台解压结果一致)
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))
// Adler32 在流尾校验:读完后显式 Close 才报错
if err := zr.Close(); err != nil {
fmt.Println("adler check failed:", err)
}
// 坏数据在 NewReader 时报 ErrHeader(魔数不对即拒收)
_, err = zlib.NewReader(bytes.NewReader([]byte("this is not zlib data")))
fmt.Println("bad input:", err)
// 解压前可先看头字节:78 是 zlib 裸格式的身份证(gzip 是 1f 8b)
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
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 {
// 预生成的固定 zlib blob(存储块模式、无时间戳,跨平台解压结果一致)
String zhex = "78010182007dff677a6970207769726520666f726d61743a206d616769632031662038622c206f6e652073746f726564206465666c61746520626c6f636b2c2063726333322b6973697a6520747261696c65722e20677a6970207769726520666f726d61743a206d616769632031662038622c206f6e652073746f726564206465666c61746520626c967e2d27";
byte[] zblob = hexBytes(zhex);
// 标准库无 zlib 包装流:手写解包——跳过 2 字节头,Inflater(true) 解裸 deflate,尾部验 Adler32
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);
// 校验 Adler32(大端,取尾部 4 字节)——Java 用异常而非 false 表达失败
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"));
// 坏数据抛 DataFormatException(BTYPE 非法即拒收)
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");
}
// 解压前可先看头字节:78 是 zlib 裸格式的身份证(gzip 是 1f 8b)
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
v26.13.1
// Node zlib:inflateSync 解 zlib 裸格式;坏数据直接抛 Error
const zlib = require("node:zlib");
// 预生成的固定 zlib blob(存储块模式、无时间戳,跨平台解压结果一致)
const zhex = "78010182007dff677a6970207769726520666f726d61743a206d616769632031662038622c206f6e652073746f726564206465666c61746520626c6f636b2c2063726333322b6973697a6520747261696c65722e20677a6970207769726520666f726d61743a206d616769632031662038622c206f6e652073746f726564206465666c61746520626c967e2d27"
const zblob = Buffer.from(zhex, "hex");
const text = zlib.inflateSync(zblob).toString();
console.log(`decoded: ${text}`);
console.log(`bytes: ${text.length}`);
// JS 的失败语义是抛异常,与 PHP 返回 false 不同
try {
zlib.inflateSync(Buffer.from("not zlib"));
} catch {
console.log("Error caught");
}
// 解压前可先看头字节:78 是 zlib 裸格式的身份证(gzip 是 1f 8b)
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
v8.6.0
// gzuncompress:解 zlib 裸格式(RFC 1950),Adler32 校验失败即返回 false
// 预生成的固定 zlib blob(存储块模式、无时间戳,跨平台解压结果一致)
$hex = "78010182007dff677a6970207769726520666f726d61743a206d616769632031662038622c206f6e652073746f726564206465666c61746520626c6f636b2c2063726333322b6973697a6520747261696c65722e20677a6970207769726520666f726d61743a206d616769632031662038622c206f6e652073746f726564206465666c61746520626c967e2d27";
$blob = hex2bin($hex);
$text = gzuncompress($blob);
echo "decoded: ", $text, "\n";
echo "bytes: ", strlen($text), "\n";
// 坏数据返回 false(魔数不对即拒收;会附 E_WARNING,生产应先校验头字节)
var_export(gzuncompress("not zlib"));
echo "\n";
// 解压前可先看头字节:78 是 zlib 裸格式的身份证(gzip 是 1f 8b)
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
v3.15.2
import zlib
# 预生成的固定 zlib blob(存储块模式、无时间戳,跨平台解压结果一致)
zhex = "78010182007dff677a6970207769726520666f726d61743a206d616769632031662038622c206f6e652073746f726564206465666c61746520626c6f636b2c2063726333322b6973697a6520747261696c65722e20677a6970207769726520666f726d61743a206d616769632031662038622c206f6e652073746f726564206465666c61746520626c967e2d27"
zblob = bytes.fromhex(zhex)
text = zlib.decompress(zblob).decode()
print(f"decoded: {text}")
print(f"bytes: {len(text)}")
# 坏数据抛 zlib.error(头或 Adler32 校验不过即拒收),与 PHP 返回 false 的失败语义不同
try:
zlib.decompress(b"not zlib")
except zlib.error:
print("zlib.error caught")
# 解压前可先看头字节:78 是 zlib 裸格式的身份证(gzip 是 1f 8b)
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
v1.99.1
// Rust 标准库无压缩设施(实战用 flate2 crate):
// 手写最小 zlib 读取器解存储块模式的 zlib 数据(含 Adler-32 校验)
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()
}
/// 解 zlib stored 块:总开销 11 = 2 头 + 5 块头 + 4 尾;失败返回 None
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() {
// 预生成的固定 zlib blob(存储块模式、无时间戳,跨平台解压结果一致)
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);
// 坏数据返回 None(头或 Adler32 校验不过)——Rust 用 Option 表达失败
println!("bad input: {:?}", zunzlib_store(b"this is not zlib data"));
// 解压前可先看头字节:78 是 zlib 裸格式的身份证(gzip 是 1f 8b)
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
v26.13.1
// Node zlib:inflateSync 解 zlib 裸格式;坏数据直接抛 Error
import { inflateSync } from "node:zlib";
// 预生成的固定 zlib blob(存储块模式、无时间戳,跨平台解压结果一致)
const zhex = "78010182007dff677a6970207769726520666f726d61743a206d616769632031662038622c206f6e652073746f726564206465666c61746520626c6f636b2c2063726333322b6973697a6520747261696c65722e20677a6970207769726520666f726d61743a206d616769632031662038622c206f6e652073746f726564206465666c61746520626c967e2d27"
const zblob = Buffer.from(zhex, "hex");
const text = inflateSync(zblob).toString();
console.log(`decoded: ${text}`);
console.log(`bytes: ${text.length}`);
// JS 的失败语义是抛异常,与 PHP 返回 false 不同
try {
inflateSync(Buffer.from("not zlib"));
} catch {
console.log("Error caught");
}
// 解压前可先看头字节:78 是 zlib 裸格式的身份证(gzip 是 1f 8b)
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
语言差异说明
C:标准库无压缩——示例手写 zlib 读取器(只解存储块,验 Adler32);真实场景用 zlib(-lz)的 inflateInit(zlib 裸格式是其默认 windowBits=15)。
C++:同 C;boost::iostreams::zlib_decompressor(注意其默认是 zlib 格式)。
C#:ZLibStream(CompressionMode.Decompress) 一条流解全格式;坏数据在首次读取时抛 InvalidDataException。
Go:zlib.NewReader 打开即校验头(坏魔数报 ErrHeader);Adler32 在 Close 时校验。
Java:标准库无 zlib 包装流——Inflater(true) 解裸 deflate,需手写跳头 + Adler32 验尾(示例);坏 BTYPE 抛 DataFormatException。
JavaScript:Node zlib.inflateSync;失败语义是抛 Error(PHP 是返回 false)。
PHP:gzuncompress 只解 zlib 裸格式——与 gzdecode 的 gzip 格式不可互解;失败返回 false 并附 E_WARNING。
Python:zlib.decompress;坏数据抛 zlib.error。
Rust:标准库无压缩——flate2::read::ZlibDecoder 是惯用解法;示例手写只解存储块的读取器。
TypeScript:同 JavaScript,Node inflateSync。