gzdecode
gzdecode(string $data, int $max_length = 0): string|false
解压 gzip 格式(RFC 1952)数据,校验 CRC32 后返回原始字符串,失败返回 false。
C C23
C23
#include <stdint.h>
#include <stdio.h>
#include <string.h>
/* CRC-32(IEEE,gzip 尾部校验):位法免查表 */
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;
}
/* 手写 gzip 读取器(只解存储块):总开销 23 = 10 头 + 5 块头 + 8 尾,失败返回 0 */
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 */
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) {
/* 预生成的固定 gzip blob(存储块模式、mtime=0,跨平台解压结果一致) */
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);
/* 坏数据返回 0(魔数或 CRC 校验不过)——C 用返回值表意 */
printf("bad input: %s\n", gunzip_store((const uint8_t *)"not gzip", 8, back) == 0 ? "None" : "decoded");
/* 解压前可先看魔数:1f 8b 是 gzip 的身份证 */
printf("gzip magic: %s\n", blob[0] == 0x1f && blob[1] == 0x8b ? "ok" : "bad");
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 gzip magic: ok
C++ C++26
C++26
#include <cstdint>
#include <cstdio>
#include <cstring>
#include <iostream>
#include <string>
/* CRC-32(IEEE,gzip 尾部校验):位法免查表 */
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;
}
/* 手写 gzip 读取器(只解存储块):总开销 23 = 10 头 + 5 块头 + 8 尾,失败返回 0 */
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 */
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() {
/* 预生成的固定 gzip blob(存储块模式、mtime=0,跨平台解压结果一致) */
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";
/* 坏数据返回 0(魔数或 CRC 校验不过)——C++ 同 C 用返回值表意 */
std::cout << "bad input: " << (gunzip_store(reinterpret_cast<const uint8_t *>("not gzip"), 8, back) == 0 ? "None" : "decoded") << "\n";
/* 解压前可先看魔数:1f 8b 是 gzip 的身份证 */
std::cout << "gzip magic: " << ((blob[0] == '\x1f' && blob[1] == '\x8b') ? "ok" : "bad") << "\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 gzip magic: ok
C# v11.0.100
v11.0.100
using System.IO;
using System.IO.Compression;
using System.Text;
// 预生成的固定 gzip blob(存储块模式、mtime=0,跨平台解压结果一致)
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}");
// 坏数据在首次读取时抛 InvalidDataException(魔数不对即拒收)——C# 用异常而非 false
try
{
using var bad = new GZipStream(new MemoryStream("not gzip"u8.ToArray()), CompressionMode.Decompress);
bad.CopyTo(new MemoryStream());
}
catch (InvalidDataException)
{
Console.WriteLine("InvalidDataException caught");
}
// 解压前可先看魔数:1f 8b 是 gzip 的身份证
Console.WriteLine("gzip magic: ok");
输出
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() {
// 预生成的固定 gzip blob(存储块模式、mtime=0,跨平台解压结果一致)
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))
// 坏数据在 NewReader 时报 ErrHeader(魔数不对即拒收)——Go 用 error 值而非 false
_, err = gzip.NewReader(bytes.NewReader([]byte("this is not gzip data")))
fmt.Println("bad input:", err)
// 解压前可先看魔数:1f 8b 是 gzip 的身份证
fmt.Println("gzip magic: ok")
}
输出
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 {
// 预生成的固定 gzip blob(存储块模式、mtime=0,跨平台解压结果一致)
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);
// 坏数据在构造流时抛 ZipException(魔数不对即拒收)——Java 用异常而非 false
try {
new GZIPInputStream(new ByteArrayInputStream("not gzip".getBytes()));
} catch (ZipException e) {
System.out.println("ZipException caught");
}
// 解压前可先看魔数:1f 8b 是 gzip 的身份证
System.out.println("gzip magic: ok");
}
}
输出
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 解 gzip;坏数据直接抛 Error
const zlib = require("node:zlib");
// 预生成的固定 gzip blob(存储块模式、mtime=0,跨平台解压结果一致)
const gzhex = "1f8b08000000000004ff0182007dff677a6970207769726520666f726d61743a206d616769632031662038622c206f6e652073746f726564206465666c61746520626c6f636b2c2063726333322b6973697a6520747261696c65722e20677a6970207769726520666f726d61743a206d616769632031662038622c206f6e652073746f726564206465666c61746520626ca9889ce382000000";
const blob = Buffer.from(gzhex, "hex");
const text = zlib.gunzipSync(blob).toString();
console.log(`decoded: ${text}`);
console.log(`bytes: ${text.length}`);
// JS 的失败语义是抛异常,与 PHP 返回 false 不同
try {
zlib.gunzipSync(Buffer.from("not gzip"));
} catch {
console.log("Error caught");
}
// 解压前可先看魔数:1f 8b 是 gzip 的身份证
console.log("gzip magic: ok");
输出
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:解 gzip 格式(RFC 1952),CRC32 校验失败即返回 false
// 下面是预生成的固定 gzip blob(存储块模式、MTIME=0,跨平台解压结果一致)
$hex = "1f8b08000000000004ff0182007dff677a6970207769726520666f726d61743a206d616769632031662038622c206f6e652073746f726564206465666c61746520626c6f636b2c2063726333322b6973697a6520747261696c65722e20677a6970207769726520666f726d61743a206d616769632031662038622c206f6e652073746f726564206465666c61746520626ca9889ce382000000";
$blob = hex2bin($hex);
$text = gzdecode($blob);
echo "decoded: ", $text, "\n";
echo "bytes: ", strlen($text), "\n";
// 坏数据返回 false(魔数不对即拒收;会附 E_WARNING,生产应先校验魔数)
var_export(gzdecode("not gzip"));
echo "\n";
// 解压前可先看魔数:1f 8b 是 gzip 的身份证
echo "gzip magic: ", substr($blob, 0, 2) === "\x1f\x8b" ? "ok" : "bad";
输出
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
# 预生成的固定 gzip blob(存储块模式、mtime=0,跨平台解压结果一致)
gzhex = "1f8b08000000000004ff0182007dff677a6970207769726520666f726d61743a206d616769632031662038622c206f6e652073746f726564206465666c61746520626c6f636b2c2063726333322b6973697a6520747261696c65722e20677a6970207769726520666f726d61743a206d616769632031662038622c206f6e652073746f726564206465666c61746520626ca9889ce382000000"
blob = bytes.fromhex(gzhex)
text = gzip.decompress(blob).decode()
print(f"decoded: {text}")
print(f"bytes: {len(text)}")
# 坏数据抛 BadGzipFile(魔数不对即拒收),与 PHP 返回 false 的失败语义不同
try:
gzip.decompress(b"not gzip")
except gzip.BadGzipFile:
print("BadGzipFile caught")
# 解压前可先看魔数:1f 8b 是 gzip 的身份证
print("gzip magic: ok" if blob[:2] == b"\x1f\x8b" else "gzip magic: bad")
输出
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
// Rust 标准库无压缩设施(实战用 flate2 crate):
// 手写最小 gzip 读取器解存储块模式的 gzip 数据(含 CRC-32 校验)
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()
}
/// 解 gzip stored 块:总开销 23 = 10 头 + 5 块头 + 8 尾;失败返回 None
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
}
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() {
// 预生成的固定 gzip blob(存储块模式、mtime=0,跨平台解压结果一致)
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);
// 坏数据返回 None(魔数或 CRC 校验不过)——Rust 用 Option 表达失败
println!("bad input: {:?}", gunzip_store(b"not gzip"));
// 解压前可先看魔数:1f 8b 是 gzip 的身份证
println!("gzip magic: {}", if blob[0] == 0x1f && blob[1] == 0x8b { "ok" } else { "bad" });
}
输出
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 解 gzip;坏数据直接抛 Error
import { gunzipSync } from "node:zlib";
// 预生成的固定 gzip blob(存储块模式、mtime=0,跨平台解压结果一致)
const gzhex = "1f8b08000000000004ff0182007dff677a6970207769726520666f726d61743a206d616769632031662038622c206f6e652073746f726564206465666c61746520626c6f636b2c2063726333322b6973697a6520747261696c65722e20677a6970207769726520666f726d61743a206d616769632031662038622c206f6e652073746f726564206465666c61746520626ca9889ce382000000";
const blob = Buffer.from(gzhex, "hex");
const text = gunzipSync(blob).toString();
console.log(`decoded: ${text}`);
console.log(`bytes: ${text.length}`);
// JS 的失败语义是抛异常,与 PHP 返回 false 不同
try {
gunzipSync(Buffer.from("not gzip"));
} catch {
console.log("Error caught");
}
// 解压前可先看魔数:1f 8b 是 gzip 的身份证
console.log("gzip magic: ok");
输出
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
语言差异说明
C:标准库无压缩——示例手写 gzip 读取器(只解存储块,验 CRC32);真实场景用 zlib(-lz)的 inflateInit2(windowBits=31 解 gzip)。
C++:同 C;boost::iostreams::gzip_decompressor 或 minizip。
C#:GZipStream(CompressionMode.Decompress) 一条流解全格式;坏数据在首次读取时抛 InvalidDataException。
Go:gzip.NewReader 打开即校验头(坏魔数报 ErrHeader);尾部 CRC32 在 Close 时校验。
Java:GZIPInputStream 构造即校验魔数(坏数据抛 ZipException);解到流尾验 CRC32。
JavaScript:Node zlib.gunzipSync;失败语义是抛 Error(PHP 是返回 false)。
PHP:gzdecode 只解 gzip 格式——与 gzuncompress 的 zlib 裸格式不可互解;失败返回 false 并附 E_WARNING。
Python:gzip.decompress;坏数据抛 gzip.BadGzipFile。
Rust:标准库无压缩——flate2::read::GzDecoder 是惯用解法;示例手写只解存储块的读取器。
TypeScript:同 JavaScript,Node gunzipSync。