mb_convert_encoding

mb_convert_encoding(array|string $string, string $to_encoding, array|string|null $from_encoding = null): array|string|false

Character encoding conversion (UTF-8/GBK/ISO-8859-1): a fixed string makes the UTF-8 -> GBK -> UTF-8 round trip lossless; compared with encode/decode, iconv, TextDecoder and Encoding across languages.

C C23

C23
#include <stdio.h>
#include <string.h>

/* Minimal UTF-8 <-> ISO-8859-1 conversion for chars <= U+00FF. Real work
   (GBK etc.) belongs to iconv()/mb_convert_encoding() - see notes. */
static size_t utf8_to_latin1(const char *in, char *out) {
    size_t n = 0;
    for (const unsigned char *p = (const unsigned char *)in; *p != 0; p++) {
        if (*p < 0x80) {
            out[n++] = (char)*p;
        } else if ((*p & 0xE0) == 0xC0 && p[1] != 0) { /* 2-byte sequence */
            unsigned int cp = ((*p & 0x1F) << 6) | (p[1] & 0x3F);
            out[n++] = cp <= 0xFF ? (char)cp : '?';
            p++;
        } else {
            out[n++] = '?';
            while (p[1] != 0 && (p[1] & 0xC0) == 0x80) p++; /* skip continuations */
        }
    }
    return n;
}

static void latin1_to_utf8(const unsigned char *in, size_t n, char *out) {
    size_t m = 0;
    for (size_t i = 0; i < n; i++) {
        unsigned char c = in[i];
        if (c < 0x80) {
            out[m++] = (char)c;
        } else {
            out[m++] = (char)(0xC0 | (c >> 6));
            out[m++] = (char)(0x80 | (c & 0x3F));
        }
    }
    out[m] = '\0';
}

int main(void) {
    const char *s = "héllo中文";
    char latin[64], back[128];
    size_t n = utf8_to_latin1(s, latin);
    for (size_t i = 0; i < n; i++) printf("%02x", (unsigned char)latin[i]);
    printf("\n"); /* 68e96c6c6f3f3f: é survives, CJK becomes '?' */
    latin1_to_utf8((const unsigned char *)latin, 5, back); /* the héllo prefix */
    printf("%d\n", strcmp(back, "héllo") == 0);            /* 1: lossless in range */
    return 0;
}
Output
68e96c6c6f3f3f
1

C++ C++26

C++26
#include <cstdio>
#include <cstring>
#include <string>

// C++ stdlib has no encoding conversion (codecvt was removed in C++26);
// this hand-written pair covers the <= U+00FF subset as a microcosm of
// "code points <-> bytes" - GBK-scale work belongs to iconv/ICU (notes)
static size_t utf8_to_latin1(const std::string& in, char *out) {
    size_t n = 0;
    for (size_t i = 0; i < in.size(); i++) {
        unsigned char c = (unsigned char)in[i];
        if (c < 0x80) {
            out[n++] = (char)c;
        } else if ((c & 0xE0) == 0xC0 && i + 1 < in.size()) { // 2-byte sequence
            unsigned int cp = ((c & 0x1F) << 6) | ((unsigned char)in[i + 1] & 0x3F);
            out[n++] = cp <= 0xFF ? (char)cp : '?';
            i++;
        } else {
            out[n++] = '?';
            while (i + 1 < in.size() && ((unsigned char)in[i + 1] & 0xC0) == 0x80) i++;
        }
    }
    return n;
}

static std::string latin1_to_utf8(const unsigned char *in, size_t n) {
    std::string out;
    for (size_t i = 0; i < n; i++) {
        unsigned char c = in[i];
        if (c < 0x80) {
            out += (char)c;
        } else {
            out += (char)(0xC0 | (c >> 6));
            out += (char)(0x80 | (c & 0x3F));
        }
    }
    return out;
}

int main() {
    std::string s = "héllo中文";
    char latin[64];
    size_t n = utf8_to_latin1(s, latin);
    for (size_t i = 0; i < n; i++) std::printf("%02x", (unsigned char)latin[i]);
    std::printf("\n"); // 68e96c6c6f3f3f: é survives, CJK becomes '?'
    std::string back = latin1_to_utf8((const unsigned char *)latin, 5);
    std::printf("%d\n", back == "héllo"); // 1: lossless in range
    return 0;
}
Output
68e96c6c6f3f3f
1

C# v11.0.100

v11.0.100
using System.Text;
Encoding.RegisterProvider(CodePagesEncodingProvider.Instance); // GBK lives outside the default set
var gbk = Encoding.GetEncoding("GBK");
var bytes = gbk.GetBytes("中文");
Console.WriteLine(Convert.ToHexString(bytes).ToLower());   // d6d0cec4
Console.WriteLine(gbk.GetString(bytes) == "中文");         // True: lossless
var latin = Encoding.GetEncoding("ISO-8859-1");
Console.WriteLine(latin.GetString(latin.GetBytes("中文"))); // chars outside -> '?'
Output
d6d0cec4
True
??

Go v1.27.4

v1.27.4
package main

import "fmt"

func main() {
	// Go strings are UTF-8 by definition; GBK conversion needs
	// golang.org/x/text/encoding/simplifiedchinese (see notes)
	s := "中文"
	fmt.Println(len(s))         // 6 bytes: the string itself is UTF-8
	fmt.Println([]rune(s))      // [20013 25991]: runes are code points
	fmt.Println(len([]rune(s))) // 2 characters
}
Output
6
[20013 25991]
2

Java v27.0.1

v27.0.1
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;

public class Main {
    public static void main(String[] args) {
        String s = "中文";
        byte[] gbk = s.getBytes(Charset.forName("GBK"));
        StringBuilder hex = new StringBuilder();
        for (byte b : gbk) hex.append(String.format("%02x", b));
        System.out.println(hex);                    // d6d0cec4
        System.out.println(new String(gbk, Charset.forName("GBK")).equals(s)); // true
        byte[] latin = s.getBytes(StandardCharsets.ISO_8859_1); // unmappable -> '?'
        System.out.println(new String(latin, StandardCharsets.ISO_8859_1));     // ??
    }
}
Output
d6d0cec4
true
??

JavaScript v26.13.1

v26.13.1
// TextDecoder can read GBK (full ICU); TextEncoder is UTF-8 only
const gbkBytes = new Uint8Array([0xd6, 0xd0, 0xce, 0xc4]); // the two CJK chars in GBK
console.log(new TextDecoder("gbk").decode(gbkBytes));     // prints the CJK word
console.log(new TextEncoder().encode("中文").length);     // 6: UTF-8 bytes
const back = new TextEncoder().encode(new TextDecoder("gbk").decode(gbkBytes));
console.log(back.length, new TextDecoder("utf-8").decode(back) === "中文");
Output
中文
6
6 true

PHP v8.6.0

v8.6.0
// fixed input keeps every step deterministic across platforms
$s = "中文";
$gbk = mb_convert_encoding($s, "GBK", "UTF-8");
echo bin2hex($gbk), "\n";                                  // d6d0cec4: first char d6d0, second cec4
$back = mb_convert_encoding($gbk, "UTF-8", "GBK");
var_dump($back === $s);                                    // round trip is lossless
echo mb_convert_encoding($s, "ISO-8859-1", "UTF-8"), "\n"; // chars outside Latin-1 -> '?'
Output
d6d0cec4
bool(true)
??

Python v3.15.2

v3.15.2
# str.encode / bytes.decode are the two conversion directions
s = "中文"
gbk = s.encode("gbk")
print(gbk.hex())                  # d6d0cec4
print(gbk.decode("gbk") == s)     # True: round trip lossless
print(s.encode("latin-1", errors="replace").decode("latin-1"))  # chars outside -> '?'
Output
d6d0cec4
True
??

Rust v1.99.1

v1.99.1
fn main() {
    // &str is always UTF-8; legacy encodings live in the encoding_rs crate
    let s = "中文";
    println!("{}", s.len());           // 6 bytes
    println!("{:?}", s.as_bytes());    // [228, 184, 173, 230, 150, 135]
    println!("{}", s.chars().count()); // 2 characters
}
Output
6
[228, 184, 173, 230, 150, 135]
2

TypeScript v26.13.1

v26.13.1
// Same runtime facilities as JS: TextDecoder("gbk") reads legacy bytes
const gbkBytes: Uint8Array = new Uint8Array([0xd6, 0xd0, 0xce, 0xc4]);
console.log(new TextDecoder("gbk").decode(gbkBytes)); // prints the CJK word
console.log(new TextEncoder().encode("中文").length); // 6: UTF-8 bytes
Output
中文
6

Language differences

C: iconv() (built into POSIX/glibc) is the system-level primitive and real conversions (GBK etc.) go through it (macOS needs -liconv at link time); the example hand-writes the <= U+00FF subset of UTF-8 <-> Latin-1 as a "code point <-> byte" microcosm — the out-of-table ? substitution matches PHP exactly.

C++: the standard library has no encoding conversion (codecvt was removed by C++26); production uses iconv (with -liconv on macOS) or ICU; the example hand-writes the same UTF-8 <-> Latin-1 microcosm as C.

C#: GBK is not in the default encoding table — first RegisterProvider(CodePagesEncodingProvider.Instance) (the CodePages provider ships with the .NET shared framework, no extra package), then GetEncoding("GBK"); unmappable characters default to ? (EncoderFallback can turn that into an exception).

Go: strings are always UTF-8 and stdlib has no legacy-encoding conversion; GBK/GB18030 needs golang.org/x/text/encoding/simplifiedchinese (a transform pipeline); the example demonstrates the rune layer.

Java: String.getBytes(Charset) / new String(bytes, Charset) convert both ways; unmappable characters default to ? (CodingErrorAction.REPORT makes it strict).

JavaScript: TextDecoder("gbk") reads legacy bytes (Node ships full ICU), but TextEncoder only emits UTF-8 — writing GBK needs a third-party library (iconv-lite etc.).

PHP: mb_convert_encoding($s, $to, $from) is mbstring's one-stop conversion; the trade-off with iconv(): mbstring ships its own encoding tables (no system iconv dependency, behavior consistent across platforms), while iconv uses the system library (more target encodings, but platform-dependent behavior). Since 8.2 the non-text encodings "Base64"/"QPrint"/"UUencode"/"HTML entities"/"7bit"/"8bit" are no longer supported — use base64_encode() for Base64; an invalid encoding throws ValueError since 8.0; from_encoding may be an array or comma list for mbstring to guess (same algorithm as mb_detect_encoding()).

Python: str.encode(codec) / bytes.decode(codec) keep the two tracks explicit; the errors parameter offers three policies: strict (default, raises UnicodeEncodeError), replace (substitutes ?), ignore.

Rust: &str is always UTF-8; legacy encodings live in the encoding_rs crate (GBK is its gb18030 view) or the encoding crate; the standard library only validates bytes as UTF-8 (str::from_utf8).

TypeScript: same runtime as JS — TextDecoder("gbk") reads legacy bytes; writing is UTF-8 only.