quoted_printable_encode / quoted_printable_decode
quoted_printable_encode(string $string): string / quoted_printable_decode(string $string): string
MIME quoted-printable (RFC 2045 §6.7): non-ASCII bytes become =XX, '=' becomes =3D, lines soft-break at 75 chars (trailing '='); encode emits CRLF per the RFC; decode only expands =XX sequences.
C C23
#include <stdio.h>
#include <string.h>
/* minimal RFC 2045 §6.7 quoted-printable encoder (no line-breaking here) */
static void qp_encode(const unsigned char *in, size_t len, char *out) {
static const char hex[] = "0123456789ABCDEF";
size_t o = 0;
for (size_t i = 0; i < len; i++) {
unsigned char b = in[i];
if (b == '=' || b > 0x7e || (b < 0x20 && b != '\n' && b != '\r')) {
out[o++] = '=';
out[o++] = hex[b >> 4];
out[o++] = hex[b & 0xf];
} else {
out[o++] = (char)b;
}
}
out[o] = '\0';
}
int main(void) {
const unsigned char raw[] = "a=1 caf\xc3\xa9"; /* é as explicit UTF-8 bytes */
char out[64] = {0}; /* zero-initialized output buffer */
qp_encode(raw, strlen((const char *)raw), out);
printf("encoded=%s\n", out);
int ascii = 1;
for (const char *p = out; *p; p++) {
if (*p < 0x20 || *p > 0x7e) ascii = 0;
}
printf("ascii only=%d\n", ascii);
return 0;
}
encoded=a=3D1 caf=C3=A9 ascii only=1
C++ C++26
#include <iostream>
#include <string>
// minimal RFC 2045 §6.7 quoted-printable encoder (no line-breaking here)
static std::string qp_encode(const std::string &raw) {
static const char *hex = "0123456789ABCDEF";
std::string out;
out.reserve(raw.size() * 3); // worst case: every byte becomes =XX
for (unsigned char b : raw) {
if (b == '=' || b > 0x7e || (b < 0x20 && b != '\n' && b != '\r')) {
out += '=';
out += hex[b >> 4];
out += hex[b & 0xf];
} else {
out += static_cast<char>(b);
}
}
return out;
}
int main() {
const std::string raw = "a=1 caf\xC3\xA9"; // é as explicit UTF-8 bytes
const std::string enc = qp_encode(raw);
std::cout << "encoded=" << enc << '\n';
bool ascii = true;
for (unsigned char c : enc) {
if (c < 0x20 || c > 0x7e) ascii = false;
}
std::cout << "ascii only=" << ascii << '\n';
return 0;
}
encoded=a=3D1 caf=C3=A9 ascii only=1
C# v11.0.100
using System;
using System.Text;
static string QpEncode(byte[] bytes)
{
// no quoted-printable in the BCL: minimal RFC 2045 §6.7 encoder
var sb = new StringBuilder();
foreach (var b in bytes)
{
int v = b & 0xff;
if (v == (int)'=' || v > 126 || (v < 32 && v != 10 && v != 13))
sb.Append('=').Append(v.ToString("X2"));
else
sb.Append((char)v);
}
return sb.ToString();
}
var enc = QpEncode(Encoding.UTF8.GetBytes("a=1 café"));
Console.WriteLine($"encoded={enc}");
Console.WriteLine($"ascii only={Array.TrueForAll(enc.ToCharArray(), c => c >= 32 && c < 127)}");
encoded=a=3D1 caf=C3=A9 ascii only=True
Go v1.27.4
package main
import (
"bytes"
"fmt"
"mime/quotedprintable"
"strings"
)
func main() {
// mime/quotedprintable implements RFC 2045 Q-encoding
var buf bytes.Buffer
w := quotedprintable.NewWriter(&buf)
w.Write([]byte("a=1 café"))
w.Close()
fmt.Println("encoded=", buf.String())
var out bytes.Buffer
r := quotedprintable.NewReader(strings.NewReader(buf.String()))
out.ReadFrom(r)
fmt.Println("roundtrip=", out.String() == "a=1 café")
}
encoded= a=3D1 caf=C3=A9 roundtrip= true
Java v27.0.1
import java.nio.charset.StandardCharsets;
public class Main {
// the JDK ships no quoted-printable codec: a minimal RFC 2045 §6.7 encoder
static String qpEncode(byte[] bytes) {
StringBuilder out = new StringBuilder();
for (byte b : bytes) {
int v = b & 0xff;
if (v == '=' || v > 126 || (v < 32 && v != '\n' && v != '\r')) {
out.append(String.format("=%02X", v));
} else {
out.append((char) v);
}
}
return out.toString();
}
public static void main(String[] args) {
byte[] raw = "a=1 café".getBytes(StandardCharsets.UTF_8);
String enc = qpEncode(raw);
System.out.println("encoded=" + enc);
System.out.println("ascii only=" + enc.chars().allMatch(c -> c >= 32 && c < 127));
}
}
encoded=a=3D1 caf=C3=A9 ascii only=true
JavaScript v26.13.1
// no quoted-printable in the standard library: a minimal RFC 2045 §6.7 encoder
function qpEncode(bytes) {
const hex = "0123456789ABCDEF";
let out = "";
for (const b of bytes) {
if (b === 0x3d || b > 0x7e || (b < 0x20 && b !== 0x0a && b !== 0x0d)) {
out += "=" + hex[(b >> 4) & 0xf] + hex[b & 0xf];
} else {
out += String.fromCharCode(b);
}
}
return out;
}
const raw = Buffer.from("a=1 café", "utf8");
const enc = qpEncode(raw);
console.log(`encoded=${enc}`);
console.log(`ascii only=${[...enc].every((c) => c.charCodeAt(0) >= 32 && c.charCodeAt(0) < 127)}`);
encoded=a=3D1 caf=C3=A9 ascii only=true
PHP v8.6.0
// RFC 2045 §6.7: non-ASCII bytes become =XX, '=' becomes =3D, and long
// lines soft-break with a trailing '=' (not exercised by this short input).
$raw = "a=1 café";
$enc = quoted_printable_encode($raw);
echo 'encoded=', $enc, "\n";
echo 'roundtrip=', quoted_printable_decode($enc) === $raw ? 'match' : 'MISMATCH', "\n";
echo 'no raw high bytes=', preg_match('/[\x80-\xFF]/', $enc) === 0 ? 'clean' : 'dirty';
encoded=a=3D1 caf=C3=A9 roundtrip=match no raw high bytes=clean
Python v3.15.2
# quopri is the standard-library quoted-printable codec (RFC 2045)
import quopri
raw = "a=1 café".encode()
enc = quopri.encodestring(raw)
print("encoded=", enc.decode())
print("roundtrip=", quopri.decodestring(enc) == raw)
encoded= a=3D1 caf=C3=A9 roundtrip= True
Rust v1.99.1
// no quoted-printable in std: a minimal RFC 2045 §6.7 encoder over UTF-8 bytes
fn qp_encode(bytes: &[u8]) -> String {
let mut out = String::new();
for &b in bytes {
if b == b'=' || b > 0x7e || (b < 0x20 && b != b'\n' && b != b'\r') {
out.push_str(&format!("={b:02X}"));
} else {
out.push(b as char);
}
}
out
}
fn main() {
let enc = qp_encode("a=1 café".as_bytes());
println!("encoded={enc}");
println!("ascii only={}", enc.bytes().all(|b| (0x20..0x7f).contains(&b)));
}
encoded=a=3D1 caf=C3=A9 ascii only=true
TypeScript v26.13.1
// no quoted-printable in the standard library: a minimal RFC 2045 §6.7 encoder
function qpEncode(bytes: Uint8Array): string {
const hex = "0123456789ABCDEF";
let out = "";
for (const b of bytes) {
if (b === 0x3d || b > 0x7e || (b < 0x20 && b !== 0x0a && b !== 0x0d)) {
out += "=" + hex[(b >> 4) & 0xf] + hex[b & 0xf];
} else {
out += String.fromCharCode(b);
}
}
return out;
}
const raw = Buffer.from("a=1 café", "utf8");
const enc = qpEncode(raw);
console.log(`encoded=${enc}`);
console.log(`ascii only=${[...enc].every((c) => c.charCodeAt(0) >= 32 && c.charCodeAt(0) < 127)}`);
encoded=a=3D1 caf=C3=A9 ascii only=true
Language differences
PHP: quoted_printable_encode (5.3+, no IMAP extension needed) encodes per RFC 2045 §6.7 — three sentences of rules: non-ASCII bytes (≥0x80) and control characters become =XX, the equals sign itself becomes =3D, and lines stay under 75 characters (a trailing '=' soft-breaks); output uses CRLF line endings (the RFC/SMTP convention — convert to LF yourself if piping into mail()); quoted_printable_decode only expands =XX (lenient about bare newlines), while iconv_mime_encode handles whole MIME headers; contrast with base64 (see that entry): QP is more compact AND human-readable for text that is mostly ASCII with a few accented characters (é shows as =C3=A9), base64 has uniform density but zero readability — mail bodies traditionally use QP, attachments use base64.
C: no QP in the standard library — the example is a minimal encoder (the =XX escaping core is ~15 lines, omitting the 75-char splitting) with a zero-initialized output buffer char out[64] = {0}; é is written as explicit UTF-8 bytes \xC3\xA9 to avoid source-encoding issues.
C++: hand-written the same way (std::string carries the bytes); out.reserve(raw.size() * 3) pre-sizes for the worst case (every byte becomes =XX) to avoid repeated reallocation.
C#: the BCL has no QP codec — production code uses MimeKit or System.Net.Mail's transport layer (which does QP internally); the example is the minimal encoder; b & 0xff normalizes the sbyte to 0-255.
Go: mime/quotedprintable (the example) is the direct standard-library match — Writer encodes, Reader decodes, with a streaming interface (it implements the 75-char splitting the minimal example omits).
Java: the JDK has no QP — Jakarta Mail's QuotedPrintableEncoder or hand-rolling; the example is the minimal encoder; String.format("=%02X", v) guarantees two uppercase hex digits.
JavaScript: no QP in the standard library — Node ecosystems use nodemailer's built-in encoder; the example is a minimal encoder iterating Buffer bytes; the all-ASCII check scans with charCodeAt.
Python: quopri (the example) is the direct standard-library match — encodestring/decodestring pair, fully isomorphic with PHP's encode/decode; email.message offers a higher-level API that picks QP/base64 automatically.
Rust: no QP in std — the third-party quoted_printable crate or hand-rolling; the example is the minimal encoder; the {b:02X} format spec yields two uppercase hex digits directly.
TypeScript: same as JavaScript; the Uint8Array parameter is type-compatible with Buffer (a Uint8Array subclass).
Teaching anchor: QP is essentially "minimal-destructive escaping to push 8-bit data through a 7-bit channel" — only bytes that MUST be escaped are, so text stays readable; the cost is severe inflation for binary data (every byte becomes 3 characters); the base64 trade-off is readability/text-friendliness vs uniform density/binary-friendliness, which is why MIME splits bodies (QP) from attachments (base64).