Bits, Bytes & Text Encoding: ASCII, Unicode, UTF-8/16, Normalization, Endianness
"Implementations of the decoding algorithm above MUST protect against decoding invalid sequences." — F. Yergeau, RFC 3629: UTF-8, a transformation format of ISO 10646, November 2003
Summary: Everything a program stores or sends is a sequence of bytes; text is bytes plus an agreement (an encoding) about which characters they mean, and most "weird character" bugs are two sides disagreeing about that agreement. Focus: Bits, integers, floats and byte order, then ASCII to Unicode to UTF-8/16/32, grapheme clusters, Persian and Arabic specifics, normalization, collation, length semantics, and the encoding choice at every boundary. Learning goal: Look at a hex dump and say which encoding it is, predict what len, strlen, mb_strlen and VARCHAR(n) count, and make Persian text store, compare and search correctly in Go, Laravel, PostgreSQL and MySQL.
This is the entry page of the Foundations path and the complete reference for how data is represented below your code: bits, bytes and words, two's complement and overflow, IEEE 754 floating point and why 0.1 + 0.2 is not 0.3, endianness and network byte order, character sets versus encodings, ASCII, Latin-1, Windows-1252 and mojibake, Unicode (code points, planes, the BMP, surrogates), UTF-8, UTF-16, UTF-32, BOMs, grapheme clusters (emoji, ZWJ, flags), the Persian and Arabic details that break real products (ZWNJ, yeh and kaf variants, digits, presentation forms, bidi marks), normalization (NFC, NFD, NFKC, NFKD), case folding and collation, string length pitfalls, and the encoding at every boundary (HTTP, JSON, databases, terminals, files, URLs). It does not re-teach Go strings in depth (see Strings, Runes, fmt Verbs, text/template & regexp), Base64/hex/percent-encoding (see Binary-to-Text Encoding) or wire formats such as JSON and Protobuf (see Serialization Formats); it links them where they continue the story.
Page map
| If you are looking for | Go to |
|---|---|
| What all 18 chapters of Foundations cover and in which order | The Foundations path |
| A table you can memorise in one minute | Everything in one minute |
| Why bytes and text need an agreement at all | Why it exists |
| ASCII, ISO 8859, Windows-1252, Unicode, UTF-8: who and when | Where it comes from |
| Bits, bytes, words, nibbles, kibibytes | Bits, bytes and words |
int8 wrapping, two's complement, PHP_INT_MAX + 1 | Two's complement and overflow |
0.1 + 0.2, NaN, infinity, float vs decimal for money | Floating point |
htons, binary.BigEndian, pack('N'), byte order in a hex dump | Endianness |
| "charset" vs "encoding", the layers of text | Character set vs encoding |
| ASCII control characters and the 7-bit table | ASCII |
é, ?, ’ in your output | Latin-1, Windows-1252 and mojibake |
Code points, planes, BMP, surrogates, U+1F600 | Unicode |
| Byte patterns, self-synchronising, overlong, BOM | UTF-8 |
Surrogate pairs, Windows/Java/JavaScript, FF FE | UTF-16 and UTF-32 |
| Emoji, ZWJ, flags, "one character" that is five code points | Grapheme clusters |
| ZWNJ, Arabic yeh/kaf, Persian digits, RTL marks, presentation forms | Persian and Arabic specifics |
| NFC vs NFD vs NFKC vs NFKD, when to normalize | Normalization |
ß, Turkish i, case folding, collations, utf8mb4 vs utf8mb3 | Collation and case folding |
len vs strlen vs mb_strlen, VARCHAR(n) per engine | String length pitfalls |
| HTTP charset, JSON, database client encoding, terminals, files, URLs | Encoding at every boundary |
iconv, file, x/text/encoding, mb_convert_encoding | Detecting and converting |
xxd, hexdump -C, reading a dump | Reading hex dumps |
| What each tool, language and database really does | Per-tool and per-product behaviour |
| Decoder algorithm, surrogate math, error messages verbatim | Mechanics |
| Double encoding, truncation, yeh/kaf search, ZWNJ in IDs: Go, Laravel, SQL fixes | Solving the classic problems |
| Which encoding, form and type for which job | Choosing |
| Monolith to distributed systems | In architecture |
| A symptom you see and the likely cause | Troubleshooting |
| Reproduce it all on your machine | Lab |
| Wrong beliefs, cheat sheet, questions, terms | Misconceptions, Cheat sheet, Self-check, Glossary |
The Foundations path: all 18 chapters
Foundations is the layer below the other paths (Go, Laravel, database, system design): how data is represented, serialized, compressed, checked and protected, and how packets travel from your laptop through Docker and Kubernetes. Read it in order the first time; every later chapter assumes the vocabulary of this one (bytes, byte order, encodings). Each chapter has Go and Laravel code and a lab.
| # | Chapter | One line |
|---|---|---|
| 01 | Bits, Bytes & Text Encoding | This page: integers, floats, byte order, Unicode, UTF-8, normalization, Persian text. |
| 02 | Binary-to-Text Encoding | How arbitrary bytes travel through text-only channels: Base64, Base32, hex, percent-encoding, data URIs. |
| 03 | Serialization Formats | JSON, Protobuf, MessagePack, Avro, CBOR, XML: schema, size, speed, evolution. |
| 04 | Compression | Entropy, Huffman, LZ77, gzip/zlib/deflate, Brotli, zstd, lz4, snappy and when each wins. |
| 05 | Checksums & Hashing | Parity, CRC32/CRC32C, xxHash, Murmur, SHA-2/3, BLAKE3, content addressing. |
| 06 | Cryptography Fundamentals | AES-GCM, ChaCha20, RSA/ECC/Ed25519, ECDH, KDFs, HMAC, signatures, randomness. |
| 07 | Password Hashing & Signed Tokens | bcrypt, Argon2, salts and peppers, HMAC-signed URLs, JWT/PASETO signing. |
| 08 | TLS in Practice | The handshake on the wire, certificates and chains, SNI/ALPN, mkcert, openssl s_client, certs in Docker and Kubernetes. |
| 09 | Network Models | OSI vs TCP/IP, encapsulation, what happens when you open a URL. |
| 10 | IP Addressing | IPv4/IPv6, private ranges, CIDR and subnet math, gateways, routing tables, ARP/NDP. |
| 11 | NAT, DHCP & Port Forwarding | NAT/PAT, port forwarding, DHCP lease flow, CGNAT, hairpin NAT. |
| 12 | DNS Resolution for Developers | Resolvers, records, TTL and caching, /etc/hosts, resolv.conf, split DNS, DNS in containers. |
| 13 | Ports, Sockets & Connections | Ephemeral ports, TIME_WAIT, keepalive, backlog, conntrack; ss, lsof, tcpdump, nc, curl, dig. |
| 14 | Firewalls | iptables/nftables, security groups, network ACLs, egress control. |
| 15 | Docker Networking | bridge, host, none, overlay, macvlan; port publishing, embedded DNS, Compose networks, the iptables rules Docker writes, MTU. |
| 16 | Kubernetes Networking | Pod network and CNI, Services, kube-proxy, CoreDNS, Ingress and Gateway API, NetworkPolicy, egress NAT. |
| 17 | VPNs & Tunnels | SSH port forwarding, bastions, WireGuard, site-to-site vs client VPN, zero-trust access. |
| 18 | Network Troubleshooting Playbook | Refused vs timeout, DNS failures, MTU/fragmentation, conntrack and port exhaustion, packet capture. |
Where this chapter's ideas come back: byte order returns in Network Models (headers are big-endian), UTF-8 and percent-encoding in Binary-to-Text Encoding, JSON's UTF-8 rule in Serialization Formats, CRC over bytes in Checksums & Hashing, and Unicode confusables in Password Hashing & Signed Tokens. Database column types and indexes for strings live in the database path (Schema Design, Normalization & Data Types).
Everything in one minute
The layers. Text is four layers stacked; most bugs mix two of them. Every row is unpacked in the concept catalogue.
| Layer | What it is | Example for the Persian word سلام | Who counts it |
|---|---|---|---|
| Grapheme cluster | What a reader calls one character | 4 | grapheme_strlen (PHP intl), uniseg (Go), Intl.Segmenter (JavaScript) |
| Code point | A number from U+0000 to U+10FFFF | 4 (U+0633 U+0644 U+0627 U+0645) | mb_strlen, utf8.RuneCountInString, PostgreSQL length() |
| Code unit | The unit an encoding form uses | UTF-8: 8, UTF-16: 4, UTF-32: 4 | strlen, len(s) in Go (UTF-8 bytes), JavaScript .length (UTF-16 units) |
| Byte | 8 bits on disk or on the wire | d8 b3 d9 84 d8 a7 d9 85 | octet_length(), LENGTH() in MySQL |
The encodings.
| Encoding | Bytes per code point | Where you meet it | The trap |
|---|---|---|---|
| ASCII | 1 (7 bits used) | Protocol keywords, HTTP methods, identifiers | Cannot hold é or ا |
| ISO 8859-1 (Latin-1) | 1 | Old Western European data, default of some old HTTP stacks | Every byte value is valid, so a wrong guess never errors, it just garbles |
| Windows-1252 | 1 | Old Windows files, "Latin-1" labels on the web | 0x80-0x9F are printable here, control codes in Latin-1 |
| Windows-1256 | 1 | Old Arabic and Persian Windows files | Has پ چ ژ گ (0x81, 0x8D, 0x8E, 0x90) but no Farsi yeh U+06CC, and its common kaf (0xDF) and yeh (0xED) decode to the Arabic U+0643 and U+064A |
| UTF-8 | 1 to 4 | The web, JSON, Go strings, Linux, databases, Git | Counting bytes as characters; BOM; overlong forms |
| UTF-16 | 2 or 4 | Windows APIs, Java, JavaScript, .NET | Byte order (BE/LE), surrogate pairs, BOM |
| UTF-32 | 4 | Internal use, some Python builds | Four times the size; still has byte order |
The five habits.
| Situation | Do this |
|---|---|
| Anything crossing a boundary (file, HTTP, DB, queue) | Say UTF-8 explicitly at both ends; never rely on a default |
| Comparing, searching or de-duplicating user text | Normalize first (NFC for storage, a lossy key for matching) |
| Cutting, counting or truncating text | Decide what the rule means (bytes, code points or graphemes) and use the function that counts that |
| Persian or Arabic input | Unify yeh and kaf (U+064A/U+06CC, U+0643/U+06A9), keep ZWNJ in stored text, strip it only in search keys |
| Multi-byte numbers on the wire | Name the byte order (network byte order is big-endian) and encode explicitly with binary.BigEndian or pack('N') |
Why it exists
A computer's memory and every network cable carry only numbers. To store a name, a price or a timestamp, two parties must agree on a mapping between meaning and bytes. For integers the mapping is small (how many bytes, which end first, signed or not). For text it is huge: thousands of writing systems, plus rules about joining, direction and case. Each historical shortcut (7 bits for English, 8 bits for one region) solved one group's problem and broke everyone else's.
| Fixed, narrow mappings (ASCII, Latin-1) | Universal mapping (Unicode + UTF-8) |
|---|---|
| One byte, one character: indexing and length are trivial | Variable width: indexing by character needs a scan |
| Only one language group per file or column | Every script in one stream |
| A wrong guess still "works" and garbles silently | A wrong guess usually errors loudly (invalid sequences) |
| Dozens of incompatible code pages | One standard; legacy code pages become conversion work |
| Sorting and case rules hard-coded per code page | Sorting and casing become locale-aware operations |
The analogy we reuse on this page: letters in envelopes. The bytes are the paper; the encoding is the language the sender wrote it in; the character set is the alphabet of that language. If the receiver opens a Persian letter assuming it is French, they get gibberish, not an error. Unicode is an agreement that everyone writes in one universal alphabet, and UTF-8 is the one handwriting everyone has agreed to read. A grapheme cluster is a "word-shape" the eye sees as one symbol, even when the sender wrote it with several strokes.
Three common misunderstandings, up front
- "A string is a list of characters, so length is the number of characters." In Go,
len(s)is bytes; in PHP,strlenis bytes; in JavaScript,.lengthis UTF-16 units; in MySQL,LENGTH()is bytes. Even "characters" is ambiguous (code points vs graphemes). - "Unicode is an encoding." Unicode is the character set (a numbering of characters). UTF-8, UTF-16 and UTF-32 are encodings of those numbers into bytes. Saying "save it as Unicode" is incomplete; say which UTF.
- "Two strings that look the same are equal."
écan be one code point (U+00E9) or two (e+ U+0301); the Persian letters yeh and kaf each have an Arabic and a Persian code point that look nearly identical. Byte comparison says "different"; users say "same".
Where it comes from
| Year | Event | Source |
|---|---|---|
| 1969 | RFC 20 describes the 7-bit ASCII character set for network interchange | RFC 20, October 1969 |
| Before Unicode | 8-bit extensions per region: ISO 8859-1 (Latin-1), Windows code pages (1252, 1256) | PostgreSQL manual encoding table lists LATIN1 as "ISO 8859-1, ECMA 94" |
| 2000 | RFC 2781 defines how UTF-16 is serialized, with BOM and the UTF-16BE/UTF-16LE labels | RFC 2781 |
| 2003 | RFC 3629 restricts UTF-8 to U+10FFFF, forbids surrogates and overlong forms | RFC 3629, November 2003 |
| 2017 | RFC 8259 (JSON) requires UTF-8 for JSON exchanged between systems | RFC 8259, December 2017 |
| Today | The WHATWG Encoding Standard defines how browsers decode; labels such as "latin1" and "iso-8859-1" are mapped to windows-1252 | WHATWG Encoding Standard |
RFC 20 is the standard form of ASCII on the network. The IETF's RFC 3629 is the UTF-8 specification every language library follows; its decoding section warns that "a naive implementation may decode the overlong UTF-8 sequence C0 80 into the character U+0000" and that "decoding invalid sequences may have security consequences". The Unicode Standard (maintained by the Unicode Consortium) assigns the numbers; Unicode Standard Annexes such as UAX #15 (normalization), UAX #29 (text segmentation) and UAX #9 (bidirectional algorithm) specify the algorithms this page uses. The site utf8everywhere.org is a widely read opinion paper that argues for UTF-8 as the default internal encoding; it is advocacy, not a standard.
For IEEE 754, the readable classic is David Goldberg's "What Every Computer Scientist Should Know About Floating-Point Arithmetic" (ACM Computing Surveys, 1991), and the Python tutorial's chapter "Floating-Point Arithmetic: Issues and Limitations" explains 0.1 with the exact binary expansion. The Go language specification states the rule for integers: they are "represented using two's complement arithmetic", and unsigned integer operations "discard high bits upon overflow, and programs may rely on 'wrap around'".
The concept catalogue
Eighteen blocks, in the order you meet them. Each has plain words, the common misunderstanding, a definition, a timeline, real scenarios, a per-product table where behaviour differs, and the fix in Go and Laravel (PHP). The runnable programs are under docs/snippets/foundations/bits-bytes-text-encoding/.
Bits, bytes and words Must-know
In plain words: A bit is one yes/no. Eight bits make a byte, the smallest thing a computer addresses. Bigger numbers use several bytes together; the group a CPU handles at once is called a word.
Common misunderstanding: "A byte is always 8 bits and a word is always 32 bits." A byte is 8 bits everywhere today (the older name octet is the same in networking), but a "word" depends on the CPU or the file format: 16 bits in the Windows API (WORD), 32 or 64 bits in processor manuals. When a spec says "word", find its definition.
Definition: bit = 0 or 1; nibble = 4 bits (one hex digit); byte/octet = 8 bits (two hex digits, 0x00 to 0xFF, 0 to 255 unsigned); word = the natural integer size of a CPU or format; n bits give 2^n values. Capacity prefixes: KB/MB/GB (SI, powers of 1000) versus KiB/MiB/GiB (powers of 1024).
value 202 (decimal) as one byte
binary 1100 1010
hex C A -> 0xCA
bit 7 (MSB) ........ bit 0 (LSB)
unsigned: 202 signed (two's complement): -54Real scenarios: the Redis string value limit of 512 MB is 512 x 1024 x 1024 bytes, not 512,000,000; a PostgreSQL smallint is 2 bytes (-32768 to 32767) and integer is 4 bytes (about 2.1 billion), which is why an auto-increment integer primary key overflows around 2.1 billion rows; a file mode 0644 is three groups of three bits; an IPv4 address is one 32-bit word.
| Unit | Size | Values | Seen as |
|---|---|---|---|
| bit | 1 bit | 2 | boolean flag, one bit in a bitmask |
| nibble | 4 bits | 16 | one hex digit |
| byte (octet) | 8 bits | 256 | uint8, byte in Go, u_char |
| 16-bit word | 2 bytes | 65,536 | uint16, TCP port numbers |
| 32-bit word | 4 bytes | 4,294,967,296 | uint32, IPv4 address, Unix time in 32 bits |
| 64-bit word | 8 bytes | 2^64 | uint64, bigint, pointers on x86-64/ARM64 |
Fix / how to use it: Go: uint8/byte, uint16, uint32, uint64, and bits.OnesCount in math/bits. Laravel: $table->unsignedSmallInteger(), unsignedInteger(), unsignedBigInteger(); use bigIncrements/id() (a bigint) for tables that may pass 2 billion rows. See ID Generation at Scale.
Two's complement and integer overflow Must-know
In plain words: Computers store negative numbers by wrapping around: with 8 bits, 255 and -1 are the same bit pattern 11111111. Add 1 to the biggest number and you land on the smallest, with no error.
Common misunderstanding: "Overflow throws an exception." In Go, C, Rust (release) and Java it silently wraps; in PHP an integer that overflows becomes a float and quietly loses precision; in Python integers grow without limit; in PostgreSQL arithmetic raises integer out of range (SQLSTATE 22003); MySQL in strict mode raises error 1264 on insert.
Definition: In two's complement an n-bit signed integer ranges from -2^(n-1) to 2^(n-1)-1. To negate a value, invert all bits and add 1. The Go specification says integers are "represented using two's complement arithmetic" and that unsigned operations "discard high bits upon overflow, and programs may rely on 'wrap around'".
int8 arithmetic, Go PHP (64-bit)
1 var i int8 = 127 1 $a = PHP_INT_MAX; // 9223372036854775807
2 i++ -> 0111 1111 + 1 = 1000 0000 2 $b = $a + 1; // float(9.2233720368547758E+18)
3 print(i) -> -128 3 var_dump($b == $a); // loses precision, no wrap
4 var u uint8 = 0; u-- -> 255Real scenarios: a 32-bit signed time_t reaches 2^31-1 at 03:14:07 UTC on 19 January 2038 and wraps negative; a quantity * price_cents multiplication in int32 goes negative for a big order; a counter column of type integer stops accepting inserts after 2,147,483,647; a "random" ID derived from a hash cast to a signed type is sometimes negative.
| Type or engine | Range / behaviour on overflow | Notes |
|---|---|---|
Go int8 / uint8 | -128..127 / 0..255, wraps silently | math/bits and math.MaxInt64 constants; constant expressions that overflow are compile errors |
Go int | 64-bit on 64-bit platforms (32 on 32-bit) | Use int64 explicitly in wire formats |
PHP int | 64-bit on 64-bit builds; overflow turns the result into float | PHP_INT_MAX, PHP_INT_SIZE; use intdiv, GMP or BCMath when exactness matters |
PostgreSQL integer | -2147483648..2147483647; error 22003 on overflow | bigint is 8 bytes; numeric is exact and unbounded |
MySQL INT | signed -2147483648..2147483647; UNSIGNED doubles the top | Strict mode: error 1264 "Out of range value"; non-strict clamps silently |
JavaScript Number | integers exact only up to 2^53-1 | Use BigInt or a string for 64-bit IDs; JSON parsers lose digits |
| SQLite | integers up to 8 bytes, stored in 1 to 8 bytes | Type affinity, not strict types, unless STRICT tables |
Fix / how to use it: In Go use the widest type that fits and check before you multiply: if a > math.MaxInt64/b { return ErrOverflow }. For money use integer cents (int64) or a decimal library. In Laravel (PHP) cast IDs from JSON as strings when a client is JavaScript, and use bigint columns. JSON number precision is covered in Serialization Formats.
Floating point (IEEE 754): why 0.1 + 0.2 is not 0.3 Must-know
In plain words: Computers store most decimals as a close binary fraction, like writing 1/3 as 0.333. The tiny error is invisible until you compare with == or add many values.
Common misunderstanding: "Floats are inexact randomly, so use more decimals." The error is deterministic and exactly specified by IEEE 754; the cure is to choose the right type (integers or decimals for money) and compare with a tolerance, not to print more digits.
Definition: A 64-bit float64 has 1 sign bit, 11 exponent bits and 52 fraction bits (32-bit float32: 1, 8, 23). A value is (-1)^sign x 1.fraction x 2^(exponent - bias). The decimal 0.1 "cannot be represented exactly as a base 2 fraction" (Python tutorial); its nearest float64 is 0x3FB999999999999A, slightly above 0.1. Special values: +Inf, -Inf, NaN (never equal to itself), and -0.
0.1 + 0.2 in float64 (Go: math.Float64bits)
1 0.1 = 0x3fb999999999999a
2 0.2 = 0x3fc999999999999a
3 sum = 0x3fd3333333333334 -> prints 0.30000000000000004
4 0.3 = 0x3fd3333333333333 -> one unit in the last place smaller
5 sum == 0.3 -> falseReal scenarios: a shopping cart total of 0.30000000000000004 shown to a customer; a price * 1.1 rounding mismatch between PHP and PostgreSQL; a test that asserts total == 0.3; a metrics pipeline summing millions of floats in a different order on two machines and getting different last digits; NaN poisoning an average.
| Representation | Exact for decimals? | Typical use | Product notes |
|---|---|---|---|
float64 / double | No | Science, graphics, metrics | Go float64; PHP float; PostgreSQL double precision; MySQL DOUBLE |
float32 / real | No, fewer digits | GPUs, ML | PostgreSQL real; MySQL FLOAT |
| Integer minor units (cents) | Yes | Money in code | Go int64; PHP int; PostgreSQL bigint |
Decimal / numeric | Yes | Money in DB, accounting | PostgreSQL numeric(12,2); MySQL DECIMAL(12,2); Go math/big or a decimal module; PHP BCMath |
Fix / how to use it: store money as integers or numeric; compare floats with an absolute or relative tolerance; never use floats as map keys or IDs. The Go program prints the bit patterns above; PHP's var_dump(0.1 + 0.2 == 0.3) is false for the same reason. In Laravel use $table->decimal('amount', 12, 2) and cast with 'amount' => 'decimal:2' (Eloquent returns a string); do arithmetic with bcadd/bcmul or Brick\Money, not with float.
Endianness and network byte order Must-know
In plain words: When a number needs several bytes, someone must decide which byte goes first. Big-endian puts the biggest byte first (like writing 1,234 as one-thousand-first); little-endian puts the smallest first.
Common misunderstanding: "Endianness matters only when I write C." It matters whenever you read or write a binary file, a custom protocol, a database page, a UTF-16/32 stream or a hash digest in raw bytes. Text in UTF-8 has no byte-order problem, because its code unit is one byte.
Definition: For the 32-bit value 0x0A0B0C0D at address a, big-endian stores 0A 0B 0C 0D at a..a+3; little-endian stores 0D 0C 0B 0A. x86-64, ARM in its default Linux/macOS/Android/iOS configuration and RISC-V are little-endian; "network byte order" is big-endian. RFC 791 (Internet Protocol) says: "When a multi-octet quantity is transmitted the most significant octet is transmitted first." htons/htonl convert host to network order; ntohs/ntohl convert back.
sender (little-endian host) and receiver (big-endian wire)
1 host value uint32 0x0A0B0C0D, memory on x86 = 0d 0c 0b 0a
2 sender binary.BigEndian.PutUint32(buf, v) -> 0a 0b 0c 0d (convert, do not memcpy)
3 wire 0a 0b 0c 0d
4 receiver binary.BigEndian.Uint32(buf) -> 0x0A0B0C0D
5 receiver forgets and reads LittleEndian -> 0x0D0C0B0A (a different number, no error)Real scenarios: TCP and UDP headers, IP addresses and ports are big-endian, so a Go server that reads a 16-bit port from a custom header with LittleEndian gets 0x5000 (20480) instead of 80; UTF-16 files from Windows are little-endian and start with FF FE; a PNG chunk length is big-endian.
| Tool or language | Big-endian | Little-endian | Host order | Notes |
|---|---|---|---|---|
Go encoding/binary | binary.BigEndian.PutUint32/Uint32, binary.Write(w, binary.BigEndian, v) | binary.LittleEndian | n/a (explicit always) | binary.NativeEndian exists in recent Go for the host order; AppendUvarint for varints |
PHP pack/unpack | N (32-bit), n (16-bit), J (64-bit) | V (32), v (16), P (64) | L, S, Q (machine order, avoid on the wire) | Format letters per the PHP manual; bin2hex to inspect |
| C / POSIX | htons, htonl, ntohs, ntohl | no standard | native | Needed for struct sockaddr_in |
| Python | struct.pack('>I', v), int.to_bytes(4, 'big') | '<I', 'little' | '=' | Prefix chooses order |
| Java | default for ByteBuffer, class files | .order(ByteOrder.LITTLE_ENDIAN) | ByteOrder.nativeOrder() | Data streams are big-endian |
| JavaScript | DataView default (big) | DataView(..., true) flag | Uint32Array uses host | A classic trap with typed arrays |
xxd, hexdump -C | show bytes in memory order | same | n/a | hexdump -C shows byte order; hexdump -x groups 16-bit words in host order and can mislead |
Fix / how to use it: Go: binary.BigEndian.PutUint32 and binary.Write (see endian/main.go). Laravel/PHP: pack('N', $v) and unpack('Nmagic/nversion/nlength', $bytes) (see Binary.php). SQL: PostgreSQL has int4send, encode(int4send(x), 'hex') returns big-endian bytes; MySQL has no equivalent, so build the bytes in the application.
// Endianness and fixed-width integers: the same 32-bit value laid out both ways.
package main
import (
"bytes"
"encoding/binary"
"fmt"
"math"
"unsafe"
)
// Header is a tiny wire format: magic, version, length. Network byte order.
type Header struct {
Magic uint32
Version uint16
Length uint16
}
func main() {
v := uint32(0x0A0B0C0D)
be := make([]byte, 4)
le := make([]byte, 4)
binary.BigEndian.PutUint32(be, v)
binary.LittleEndian.PutUint32(le, v)
fmt.Printf("value : %#08x\n", v)
fmt.Printf("big-endian : % x\n", be)
fmt.Printf("little : % x\n", le)
// What does THIS machine do natively?
probe := uint16(1)
if *(*byte)(unsafe.Pointer(&probe)) == 1 {
fmt.Println("host order : little-endian")
} else {
fmt.Println("host order : big-endian")
}
// Encode a struct to the wire (network order) and decode it back.
var buf bytes.Buffer
h := Header{Magic: 0xCAFEBABE, Version: 2, Length: 513}
if err := binary.Write(&buf, binary.BigEndian, h); err != nil {
panic(err)
}
fmt.Printf("wire bytes : % x\n", buf.Bytes())
var back Header
if err := binary.Read(&buf, binary.BigEndian, &back); err != nil {
panic(err)
}
fmt.Printf("decoded : %+v\n", back)
// Reading little-endian bytes as big-endian gives a different number.
wrong := binary.BigEndian.Uint32(le)
fmt.Printf("misread : %#08x (expected %#08x)\n", wrong, v)
// Varint (protobuf, SQLite, Go gob): 300 takes two bytes.
vb := binary.AppendUvarint(nil, 300)
fmt.Printf("uvarint 300: % x\n", vb)
// Floating point: 0.1 + 0.2 and the exact bits.
a, b := 0.1, 0.2
sum := a + b
fmt.Println("0.1+0.2 :", sum, sum == 0.3)
fmt.Printf("bits(0.1) : %#016x\n", math.Float64bits(a))
fmt.Printf("bits(sum) : %#016x\n", math.Float64bits(sum))
fmt.Printf("bits(0.3) : %#016x\n", math.Float64bits(0.3))
fmt.Println("near-equal :", math.Abs(sum-0.3) < 1e-9)
// Integer overflow wraps silently in Go (two's complement).
var i8 int8 = 127
i8++
var u8 uint8 = 0
u8--
fmt.Println("int8 127+1 :", i8, " uint8 0-1:", u8)
minusOne := int32(-1)
fmt.Printf("-1 as int32 bits: %#08x\n", uint32(minusOne))
}Real output of go run ./endian on an Apple-silicon Mac (little-endian):
value : 0x0a0b0c0d
big-endian : 0a 0b 0c 0d
little : 0d 0c 0b 0a
host order : little-endian
wire bytes : ca fe ba be 00 02 02 01
decoded : {Magic:3405691582 Version:2 Length:513}
misread : 0x0d0c0b0a (expected 0x0a0b0c0d)
uvarint 300: ac 02
0.1+0.2 : 0.30000000000000004 false
bits(0.1) : 0x3fb999999999999a
bits(sum) : 0x3fd3333333333334
bits(0.3) : 0x3fd3333333333333
near-equal : true
int8 127+1 : -128 uint8 0-1: 255
-1 as int32 bits: 0xffffffffThe wire bytes 00 02 and 02 01 show Version=2 and Length=513 (0x0201): reading them in the wrong order would give 512 and 258. PHP version:
<?php
declare(strict_types=1);
// Byte order and text in plain PHP. Run: php Binary.php
$value = 0x0A0B0C0D;
echo bin2hex(pack('N', $value)), PHP_EOL; // 0a0b0c0d big-endian (network byte order)
echo bin2hex(pack('V', $value)), PHP_EOL; // 0d0c0b0a little-endian
echo bin2hex(pack('J', $value)), PHP_EOL; // 000000000a0b0c0d unsigned 64-bit big-endian
echo bin2hex(pack('P', $value)), PHP_EOL; // 0d0c0b0a00000000 unsigned 64-bit little-endian
// Decode a wire header: magic (N), version (n), length (n).
$wire = hex2bin('cafebabe00020201');
['magic' => $magic, 'version' => $version, 'length' => $length] = unpack('Nmagic/nversion/nlength', $wire);
printf("magic=%08x version=%d length=%d\n", $magic, $version, $length);
// strlen counts bytes, mb_strlen counts code points, grapheme_strlen counts user-perceived characters.
$s = "\u{0633}\u{0644}\u{0627}\u{0645}"; // four Persian letters
$family = "\u{1F468}\u{200D}\u{1F469}\u{200D}\u{1F467}";
printf("%d %d\n", strlen($s), mb_strlen($s, 'UTF-8')); // 8 4
printf("%d %d %d\n", strlen($family), mb_strlen($family, 'UTF-8'), grapheme_strlen($family)); // 18 5 1
// Slicing: substr cuts bytes, mb_substr cuts code points.
var_dump(bin2hex(substr($s, 0, 3))); // "d8b3d9" (broken)
var_dump(mb_substr($s, 0, 2, 'UTF-8')); // two letters
// Float comparison: never ==.
var_dump(0.1 + 0.2 == 0.3); // false
var_dump(abs((0.1 + 0.2) - 0.3) < 1e-9); // true
var_dump(PHP_INT_MAX + 1); // float(9.2233720368547758E+18): PHP promotes, it does not wrap
// Conversion and detection.
$latin1 = "caf\xE9";
var_dump(mb_check_encoding($latin1, 'UTF-8')); // false
var_dump(mb_convert_encoding($latin1, 'UTF-8', 'ISO-8859-1')); // the string cafe with an acute e
var_dump(mb_detect_encoding($latin1, ['UTF-8', 'ISO-8859-1'], true)); // "ISO-8859-1"
var_dump(iconv('UTF-8', 'ASCII//TRANSLIT', "caf\u{00E9}")); // "cafe" on glibc; platform dependentCharacter set vs encoding Must-know
In plain words: A character set is a numbered list of characters ("ا is number 1575"). An encoding says how to write that number as bytes. Same list, many ways to write the numbers.
Common misunderstanding: "charset=utf8 means the text is Unicode characters." In HTTP and MIME, charset is an encoding label. In MySQL, "character set" is also an encoding, and utf8 meant a 3-byte-only subset. In older code pages the charset and the encoding were the same thing, which is why the words got mixed.
Definition: Coded character set: a mapping from characters to non-negative integers (code points). Character encoding form: a mapping from code points to sequences of code units (UTF-8: 8-bit units; UTF-16: 16-bit; UTF-32: 32-bit). Encoding scheme: the form plus a byte order (UTF-16BE, UTF-16LE). A code page (Windows-1252) is a charset and encoding in one.
"ا" (ARABIC LETTER ALEF)
1 character set Unicode -> code point U+0627
2 encoding form UTF-8 -> code unit sequence D8 A7
3 encoding form UTF-16 -> code unit 0627
4 encoding scheme UTF-16LE -> bytes 27 06
5 legacy Windows-1256 -> single byte C7 (not Unicode at all)Real scenarios: an API returns Content-Type: application/json; charset=utf-8 (JSON ignores a charset parameter, see RFC 8259); a MySQL column declared CHARACTER SET latin1 silently stores ? for Persian letters; a CSV exported by Excel as "Unicode Text" is UTF-16LE with a BOM; file -i reports charset=iso-8859-1 for a file that is really a mix.
| Term | Meaning | Example | Where it is configured |
|---|---|---|---|
| Character set / repertoire | Which characters exist | Unicode, ASCII | Standards |
| Code point | A character's number | U+0627 | Unicode tables |
| Encoding form | Code point to code units | UTF-8, UTF-16 | Libraries |
| Encoding scheme | Form plus byte order | UTF-16LE | File label, BOM |
| Code page | Legacy charset and encoding in one | Windows-1256 | Windows, old databases |
charset in HTTP/MIME | An encoding label | charset=utf-8 | Content-Type header |
| MySQL "character set" | An encoding of a column or connection | utf8mb4 | Column, table, server, connection |
| PostgreSQL "encoding" | Database-level encoding | UTF8 | CREATE DATABASE ... ENCODING |
Fix / how to use it: always set the encoding explicitly at every layer (Encoding at every boundary); in Go every string is a byte sequence assumed to be UTF-8, in PHP a string is just bytes and the encoding is chosen per function (mb_*, iconv).
ASCII Important
In plain words: ASCII is the 128-character table of English letters, digits, punctuation and a few control codes, using values 0 to 127.
Common misunderstanding: "ASCII is 8-bit." ASCII is 7-bit; the eighth bit was used differently by every vendor, which is why Latin-1, Windows-1252 and a hundred code pages exist. Every valid ASCII text is also valid UTF-8, with the same bytes.
Definition: 0x00-0x1F and 0x7F are control codes (NUL, TAB 0x09, LF 0x0A, CR 0x0D, ESC 0x1B, DEL 0x7F); 0x20 is space; 0x30-0x39 digits; 0x41-0x5A uppercase; 0x61-0x7A lowercase (uppercase and lowercase differ by one bit, 0x20); 0x7E is ~. RFC 20 is the network-interchange description.
"Hi!\n" as bytes
1 H 0x48 0100 1000
2 i 0x69 0110 1001
3 ! 0x21 0010 0001
4 LF 0x0A 0000 1010
5 'H' | 0x20 -> 'h' (bit 5 toggles case in ASCII)Real scenarios: HTTP header names and methods, SQL keywords and many protocol commands are ASCII; line ending differences (LF on Unix, CRLF 0D 0A in HTTP and SMTP) break shell scripts shipped from Windows; \0 (NUL) terminates C strings and can truncate a value passed to a native library.
| Range | Characters | Remark |
|---|---|---|
| 0x00-0x1F, 0x7F | Control codes | Strip or reject in identifiers and log lines |
| 0x20-0x2F | Space, !"#$%&'()*+,-./ | Percent-encoding targets (see Binary-to-Text Encoding) |
| 0x30-0x39 | 0-9 | Only these are digits for ctype_digit and Laravel's digits rule |
| 0x41-0x5A, 0x61-0x7A | A-Z, a-z | Case differs by bit 0x20 |
Fix / how to use it: validate identifiers with an ASCII allow-list (^[a-z0-9_]+$); in Go compare ASCII case-insensitively with strings.EqualFold (full Unicode folding) or bytes.EqualFold; Laravel: 'regex:/^[a-z0-9_]+$/' and Str::ascii() for transliteration (see Solving the classic problems).
Latin-1, Windows-1252 and mojibake Must-know
In plain words: Mojibake is what you see when bytes written in one encoding are read as another: café turns into café. The bytes did not change; the reader guessed the wrong table.
Common misunderstanding: "I will just try encodings until it looks right." Single-byte encodings accept every byte, so a wrong guess never errors and can look "almost right" for English text while destroying the rest. Guessing is a last resort, and the real fix is to record the encoding where the data is produced.
Definition: ISO 8859-1 (Latin-1) maps byte 0xE9 to é and leaves 0x80-0x9F as invisible control codes. Windows-1252 maps most of 0x80-0x9F to printable characters (0x80 is the euro sign, 0x92 is the curly apostrophe). The WHATWG Encoding Standard treats the labels latin1 and iso-8859-1 as windows-1252, so browsers decode "Latin-1" pages as Windows-1252. Windows-1256 is the Arabic/Persian Windows code page (0xD3 0xE1 0xC7 0xE3 is سلام).
"é" stored as UTF-8, read as Windows-1252, stored as UTF-8 again
1 UTF-8 bytes of é c3 a9
2 read as cp1252 c3 -> "Ã" a9 -> "©" (a 2-character mojibake)
3 saved as UTF-8 c3 83 c2 a9 (double encoding)
4 read as cp1252 again "Ã" "ƒ" "Â" "©" ... grows each round tripReal scenarios: ’ instead of a curly apostrophe (UTF-8 bytes E2 80 99 read as cp1252); question marks in a MySQL table created as latin1 after inserting Persian; a customer's name "Müller" showing as "Müller" in an email; a CSV saved by Excel in the Windows-1256 code page unreadable in a UTF-8 import.
Real commands and output on this machine (macOS, iconv and file):
$ printf 'caf\xc3\xa9\n' > a.txt; printf 'caf\xe9\n' > b.txt; file -I a.txt b.txt
a.txt: text/plain; charset=utf-8
b.txt: text/plain; charset=iso-8859-1
$ printf 'café' | iconv -f ISO-8859-1 -t UTF-8 | xxd # UTF-8 bytes misread as Latin-1
00000000: 6361 66c3 83c2 a9 caf....| Mojibake you see | Cause | Fix |
|---|---|---|
é, ü, è | UTF-8 text decoded as Latin-1/cp1252 | Decode as UTF-8; repair by encode-to-cp1252 then decode-as-UTF-8 |
’, “, â€" | UTF-8 punctuation decoded as cp1252 | Same |
سلام for Persian | UTF-8 Persian decoded as cp1252 | Same; every Persian letter becomes two Latin symbols |
? or Ø replacing letters | Lossy conversion to a narrow charset | Data lost; re-import from source; switch to UTF-8 |
U+FFFD (replacement character) | Decoder met invalid bytes | Find the producer; do not store it |
| Letters correct but reversed order | Bidi/visual-order data | See Persian and Arabic specifics |
Fix / how to use it: Go: decode legacy data with golang.org/x/text/encoding/charmap (see convert/main.go below). PHP: mb_convert_encoding($s, 'UTF-8', 'Windows-1256') or iconv('Windows-1256', 'UTF-8//IGNORE', $s). SQL: CONVERT(CONVERT(col USING latin1) USING utf8mb4) repairs a double-encoded MySQL column after a backup (see Solving the classic problems).
// Detecting and repairing mojibake, and converting legacy encodings.
package main
import (
"fmt"
"io"
"strings"
"golang.org/x/text/encoding/charmap"
"golang.org/x/text/encoding/unicode"
"golang.org/x/text/transform"
)
func main() {
// UTF-8 bytes of "\u00E9" read as Windows-1252 become "é": classic mojibake.
good := "caf\u00E9"
moji, _ := charmap.Windows1252.NewDecoder().String(good)
fmt.Printf("UTF-8 read as cp1252: %q\n", moji)
// Repair: encode back to cp1252 bytes, then reinterpret them as UTF-8.
raw, err := charmap.Windows1252.NewEncoder().String(moji)
if err != nil {
panic(err)
}
fmt.Printf("repaired : %q\n", raw)
// Real legacy input: ISO-8859-1 bytes to UTF-8.
latin1 := []byte{0x63, 0x61, 0x66, 0xE9}
utf8s, _ := charmap.ISO8859_1.NewDecoder().Bytes(latin1)
fmt.Printf("latin1 -> utf8 : % x -> % x\n", latin1, utf8s)
// Windows-1252 differs from Latin-1 in 0x80-0x9F: 0x80 is the euro sign.
euro, _ := charmap.Windows1252.NewDecoder().String("\x80")
c1, _ := charmap.ISO8859_1.NewDecoder().String("\x80")
fmt.Printf("0x80 cp1252=%q latin1=%U\n", euro, []rune(c1))
// Persian legacy: Windows-1256 (Arabic) decodes D3 E1 C7 E3 as the word salam.
fa, _ := charmap.Windows1256.NewDecoder().String("\xd3\xe1\xc7\xe3")
fmt.Printf("windows-1256 : %q\n", fa)
// UTF-16 with BOM handling, as Windows tools and Excel "Unicode text" emit.
u16le := unicode.UTF16(unicode.LittleEndian, unicode.UseBOM)
enc, _ := io.ReadAll(transform.NewReader(strings.NewReader("سلام"), u16le.NewEncoder()))
fmt.Printf("UTF-16LE + BOM : % x\n", enc)
dec, _ := io.ReadAll(transform.NewReader(strings.NewReader(string(enc)), u16le.NewDecoder()))
fmt.Printf("back : %q\n", dec)
// Strict vs lossy: encoding to ASCII fails for non-ASCII input.
_, err = charmap.Windows1252.NewEncoder().String("سلام")
fmt.Println("cp1252 encode error :", err)
}Real output of go run ./convert:
UTF-8 read as cp1252: "café"
repaired : "café"
latin1 -> utf8 : 63 61 66 e9 -> 63 61 66 c3 a9
0x80 cp1252="€" latin1=[U+0080]
windows-1256 : "سلام"
UTF-16LE + BOM : ff fe 33 06 44 06 27 06 45 06
back : "سلام"
cp1252 encode error : encoding: rune not supported by encoding.Unicode: code points, planes, the BMP and surrogates Must-know
In plain words: Unicode gives every character in every script a number, called a code point, written U+ and hex: ا is U+0627, 😀 is U+1F600.
Common misunderstanding: "A code point is one character on screen." A code point is a number in the table. A visible character may be several code points (a letter plus a combining mark, an emoji with a skin tone), and some code points are invisible (U+200C ZERO WIDTH NON-JOINER, U+FEFF).
Definition: the code space is U+0000 to U+10FFFF (1,114,112 values) divided into 17 planes of 65,536 each. Plane 0 is the Basic Multilingual Plane (BMP, U+0000-U+FFFF: Latin, Arabic, Persian, Chinese common characters); planes 1 and 2 hold emoji, historic scripts and rare CJK (the Supplementary Multilingual and Ideographic Planes). U+D800-U+DFFF are surrogates: code points reserved for UTF-16 and never valid characters in UTF-8 or on their own. Unicode categories (General Category) include Lo letter, Mn non-spacing mark, Cf format control (ZWNJ, ZWJ, BOM, bidi marks), Cc control. The Unicode Character Database (UnicodeData.txt) lists names, for example 200C;ZERO WIDTH NON-JOINER;Cf.
code point -> where
1 U+0041 A plane 0 (BMP) 1 UTF-8 byte
2 U+0627 ا ARABIC LETTER ALEF plane 0 (BMP) 2 UTF-8 bytes
3 U+20AC € EURO SIGN plane 0 (BMP) 3 UTF-8 bytes
4 U+1F600 😀 GRINNING FACE plane 1 (SMP) 4 UTF-8 bytes, surrogate pair in UTF-16
5 U+D83D (surrogate, not a character) -> invalid on its own in UTF-8Real scenarios: MySQL utf8 (utf8mb3) cannot store U+1F600 and fails with error 1366 Incorrect string value: '\xF0\x9F\x98\x80'; a JavaScript "😀".length is 2; a Go []rune(s) converts invalid bytes to U+FFFD; a regular expression . in an old engine splits an emoji in half; a font shows a "tofu" box for an unassigned code point.
| Concept | Range or value | Remark |
|---|---|---|
| Code space | U+0000..U+10FFFF | 1,114,112 code points |
| BMP (plane 0) | U+0000..U+FFFF | One UTF-16 unit; 1 to 3 UTF-8 bytes |
| Supplementary planes | U+10000..U+10FFFF | Two UTF-16 units (a surrogate pair); 4 UTF-8 bytes |
| Surrogates | U+D800..U+DFFF | Not scalar values; invalid in UTF-8 |
| Scalar value | any code point except surrogates | What Go's rune and well-formed UTF-8 can carry |
| Noncharacters | U+FFFE, U+FFFF, U+FDD0..FDEF and others | Reserved for internal use |
| Replacement character | U+FFFD | What decoders emit for invalid input |
| Private use | U+E000..U+F8FF, planes 15-16 | Application-defined |
Fix / how to use it: in Go a rune is an int32 code point; for i, r := range s iterates code points with their byte offsets; utf8.ValidString checks well-formedness. In PHP use mb_ord/mb_chr, mb_str_split, IntlChar::charName. In SQL, PostgreSQL ascii()/chr() take code points in a UTF8 database; MySQL ORD() returns the multi-byte value and CHAR(... USING utf8mb4) builds it.
UTF-8 Must-know
In plain words: UTF-8 writes a code point as 1 to 4 bytes. ASCII stays one byte, so English text looks unchanged; other scripts take 2 to 4 bytes.
Common misunderstanding: "UTF-8 is variable, so it is slow and unsafe to slice." Slicing by byte offset is safe if the offset lands on a character boundary, and UTF-8 is self-synchronising, so you can always find the next boundary by skipping continuation bytes. What is unsafe is cutting at an arbitrary byte.
Definition: the first byte tells you the length; continuation bytes always look like 10xxxxxx. RFC 3629 limits UTF-8 to U+10FFFF, forbids the surrogate range, and says decoders "MUST protect against decoding invalid sequences", with the overlong example C0 80 for U+0000 and the surrogate-pair example ED A1 8C ED BE B4.
decoding the bytes D8 B3 (a Persian letter)
1 D8 = 1101 1000 -> starts with 110 -> 2-byte sequence, payload bits 11000
2 B3 = 1011 0011 -> starts with 10 -> continuation, payload bits 110011
3 join payloads -> 11000 110011 = 0x633 -> U+0633 س
4 check -> not overlong (needs >= U+0080), not a surrogate, <= U+10FFFF -> accept
5 bytes C0 80 -> 110 00000 10 000000 -> would decode to U+0000 -> overlong -> rejectReal scenarios: security filters that check for / or NUL and then decode C0 AF as / (the classic overlong path-traversal bug); a UTF-8 BOM (EF BB BF) at the start of a JSON file or a PHP file causing "headers already sent" or parse errors; a database column of VARCHAR(255) receiving 255 characters of Persian text taking 510 bytes; logs mixing Latin-1 lines into a UTF-8 file so that a viewer shows boxes.
| Property | UTF-8 | Consequence |
|---|---|---|
| ASCII-compatible | Bytes 0x00-0x7F mean the same as ASCII | Old parsers, strchr(',') and / splitting keep working |
| Self-synchronising | Lead and continuation bytes are distinguishable | Seek to any offset and resynchronise in at most 3 bytes |
| No byte-order issue | Code unit is one byte | A BOM is unnecessary; RFC 3629 notes it is always EF BB BF |
| Sorts like code points | Byte order equals code point order | memcmp ordering equals code point ordering (not linguistic order) |
| Overlong and surrogate forms invalid | Strict decoders reject them | Treat decoder errors as invalid input |
| Size per script | Latin 1 byte (+accents 2), Arabic/Persian/Hebrew/Greek/Cyrillic 2, most CJK 3, emoji 4 | Persian text is about twice the byte size of ASCII |
Fix / how to use it: validate with utf8.ValidString (Go) or mb_check_encoding($s, 'UTF-8') (PHP) at the edge, reject or replace invalid input once, and never strip a BOM by hand in the middle of a pipeline (use bytes.TrimPrefix(b, []byte{0xEF,0xBB,0xBF}) at file ingest). JSON must not start with a BOM: RFC 8259 says "Implementations MUST NOT add a byte order mark (U+FEFF) to the beginning of a networked-transmitted JSON text".
UTF-16 and UTF-32 Important
In plain words: UTF-16 uses 2 bytes for most characters and 4 bytes for the rest (emoji, rare scripts). UTF-32 always uses 4. Both have the byte-order question UTF-8 avoids.
Common misunderstanding: "UTF-16 is two bytes per character, so length is easy." Code points above U+FFFF take two 16-bit units (a surrogate pair), so UTF-16 is variable-width too, and JavaScript .length, Java String.length() and C# String.Length count units, not characters.
Definition: for a code point cp at or above U+10000, v = cp - 0x10000, high surrogate = 0xD800 + (v >> 10), low surrogate = 0xDC00 + (v & 0x3FF). For U+1F600: v = 0xF600, high = 0xD83D, low = 0xDE00. RFC 2781 defines the labels UTF-16BE (big-endian), UTF-16LE (little-endian) and plain UTF-16 (which may begin with a BOM, U+FEFF, to signal the order: FE FF big, FF FE little).
"سلام" and "😀" in the three UTF forms (BE unless stated)
1 UTF-8 d8 b3 d9 84 d8 a7 d9 85 | f0 9f 98 80
2 UTF-16BE 06 33 06 44 06 27 06 45 | d8 3d de 00
3 UTF-16LE 33 06 44 06 27 06 45 06 | 3d d8 00 de
4 UTF-16+BOM fe ff 06 33 06 44 06 27 06 45 | macOS iconv writes the BOM, big-endian
5 UTF-32BE 00 00 06 33 00 00 06 44 ... | 00 01 f6 00Real scenarios: Windows APIs and .NET use UTF-16LE; Java and JavaScript strings are UTF-16 internally; Excel's "Unicode Text" is UTF-16LE with BOM; an iconv job from UTF-16 without BOM guesses wrong order; Go's unicode/utf16 converts for Windows syscalls.
| Platform | Internal string form | length counts | Note |
|---|---|---|---|
| Go | UTF-8 bytes | bytes (len) | utf16.Encode([]rune(s)) for UTF-16 |
| PHP | bytes, any encoding | bytes (strlen); mb_strlen counts code points | mb_convert_encoding($s, 'UTF-16LE', 'UTF-8') |
| JavaScript | UTF-16 units | units (.length) | [...s].length counts code points, Intl.Segmenter graphemes |
| Java / C# | UTF-16 units | units | codePointCount in Java |
| Python 3 | code points (flexible representation) | code points | len('😀') is 1 |
| PostgreSQL | stored as UTF-8 in a UTF8 database | length() counts characters | octet_length() bytes |
| MySQL | by column charset | CHAR_LENGTH characters, LENGTH bytes | utf8mb4 max 4 bytes per character |
| SQL Server | nvarchar is UTF-16 (UCS-2 semantics unless _SC collation) | n counts byte-pairs | Microsoft: "n never defines numbers of characters" for nchar(n)/nvarchar(n) |
Fix / how to use it: keep UTF-8 on disk, on the wire and in databases; convert to UTF-16 only at Windows, Java or JavaScript boundaries; always label UTF-16 with its order (UTF-16LE) or a BOM.
Grapheme clusters vs code points vs bytes Must-know
In plain words: What a person calls one character can be several code points: é can be e plus an accent mark; 🇮🇷 is two regional-indicator letters; a family emoji is three people glued with invisible joiners.
Common misunderstanding: "len([]rune(s)) is the number of characters." It is the number of code points. For a family emoji it is 5, for the flag of Iran it is 2, for e + combining acute it is 2, and each of those is one grapheme.
Definition: a grapheme cluster ("user-perceived character") is defined by UAX #29, which says it "describes guidelines for determining default segmentation boundaries between certain significant text elements: grapheme clusters ("user-perceived characters"), words, and sentences". Extended grapheme clusters join base letters with combining marks (Extend), emoji sequences with ZWJ (U+200D), regional-indicator pairs (flags), and Hangul syllable pieces.
one family emoji "👨👩👧"
1 grapheme clusters 1
2 code points 5 U+1F468 U+200D U+1F469 U+200D U+1F467
3 UTF-16 units 8 d83d dc68 200d d83d dc69 200d d83d dc67
4 UTF-8 bytes 18 f0 9f 91 a8 e2 80 8d f0 9f 91 a9 e2 80 8d f0 9f 91 a7
5 s[:3] in Go f0 9f 91 -> invalid UTF-8, renders as U+FFFDReal scenarios: a "max 20 characters" username field accepts 20 code points but shows 8 visible symbols; a "reverse string" function reverses combining marks onto the wrong letter; a text editor deletes half of an emoji family; truncating "🇮🇷" to one code point leaves a lone regional indicator; a Persian name with ZWNJ counts 8 code points but 7 graphemes.
Real output of go run ./norm (the last part counts graphemes with github.com/rivo/uniseg):
"é" bytes=2 runes=1 graphemes=1
"é" bytes=3 runes=2 graphemes=1
"👨👩👧" bytes=18 runes=5 graphemes=1
"🇮🇷" bytes=8 runes=2 graphemes=1
"👍🏽" bytes=8 runes=2 graphemes=1
"میخواهم" bytes=17 runes=8 graphemes=7| Library | Counts graphemes with | Notes |
|---|---|---|
| Go | github.com/rivo/uniseg (GraphemeClusterCount, NewGraphemes) | Standard library has no grapheme API; x/text does not segment graphemes |
| PHP | grapheme_strlen, grapheme_substr, grapheme_extract (ext-intl) | mb_* counts code points only |
| JavaScript | Intl.Segmenter(undefined, {granularity: 'grapheme'}) | .length is UTF-16 units |
| PostgreSQL | no built-in grapheme length | Use an extension or count in the app |
| MySQL | no built-in grapheme length | CHAR_LENGTH counts code points |
Fix / how to use it: decide per rule: storage limits count bytes or code points (what the database does), display limits count graphemes, and "max N characters" validation for people should count graphemes (grapheme_strlen in PHP, uniseg in Go) while the database column stays generous (see String length pitfalls).
Persian and Arabic specifics Must-know
In plain words: Persian shares letters with Arabic, but several look-alike letters have different code points, a special invisible space (ZWNJ) is part of correct spelling, and digits come in three sets. Real data mixes them, and a search or uniqueness check that compares bytes breaks.
Why the mix exists: in Windows-1256, byte 0xED decodes to Arabic yeh (U+064A) and 0xDF to Arabic kaf (U+0643); the code page has no Farsi yeh at all (checked with Python: chr(0x06CC).encode('cp1256', errors='replace') gives b'?'). Decades of Persian data written through that code page therefore carry the Arabic letters.
Common misunderstanding: "Persian is just Arabic text, so any Arabic handling is fine." Keyboards and legacy software produce Arabic yeh (U+064A ي) and Arabic kaf (U+0643 ك) where Persian typists expect Farsi yeh (U+06CC ی) and keheh (U+06A9 ک). They look nearly identical, they are different code points, and NFC/NFKC do not unify them, so کیان and كيان are different strings. Another trap: removing every invisible character removes the ZWNJ that separates می and خواهم.
Definition: the key characters, with real names from UnicodeData.txt:
| Code point | Name | Role |
|---|---|---|
| U+064A | ARABIC LETTER YEH | Arabic yeh; two dots below in the initial and medial forms; common in Arabic keyboards |
| U+06CC | ARABIC LETTER FARSI YEH | Persian yeh, the correct letter in Persian text |
| U+0649 | ARABIC LETTER ALEF MAKSURA | Dotless yeh-like letter in Arabic; sometimes typed for yeh |
| U+0643 | ARABIC LETTER KAF | Arabic kaf |
| U+06A9 | ARABIC LETTER KEHEH | Persian kaf, the correct letter in Persian text |
| U+0629, U+0647, U+06C0 | TEH MARBUTA, HEH, HEH WITH YEH ABOVE | Sometimes interchanged in noisy data |
| U+200C | ZERO WIDTH NON-JOINER (ZWNJ), category Cf | Prevents joining without a visible space: میخواهم |
| U+200D | ZERO WIDTH JOINER (ZWJ) | Forces joining; also glues emoji |
| U+200E / U+200F | LEFT-TO-RIGHT MARK / RIGHT-TO-LEFT MARK | Invisible bidi direction hints |
| U+202B..U+202E, U+2066..U+2069 | Embedding, override and isolate controls | Can reorder text visually; strip from identifiers |
| U+061C | ARABIC LETTER MARK | Direction mark used in Arabic text |
| U+0640 | ARABIC TATWEEL (kashida) | Elongation line, decoration only |
| U+064B..U+065F, U+0670 | Harakat (fatha, kasra, shadda...), superscript alef | Vowel marks; usually dropped for search |
| U+06F0..U+06F9 | EXTENDED ARABIC-INDIC DIGITS ۰-۹ | Persian digits |
| U+0660..U+0669 | ARABIC-INDIC DIGITS ٠-٩ | Arabic digits; ٤ ٥ ٦ differ in shape from ۴ ۵ ۶ |
| U+066B, U+066C | ARABIC DECIMAL SEPARATOR, THOUSANDS SEPARATOR | Punctuation inside Arabic-digit numbers |
| U+FB50..U+FDFF, U+FE70..U+FEFF | Arabic Presentation Forms-A and -B | Pre-shaped glyph forms (isolated, initial, medial, final); compatibility characters from old encodings |
The W3C Arabic Layout Requirements explain ZWNJ: "this character is called U+200C ZERO WIDTH NON-JOINER, or ZWNJ for short", used when "two Arabic letters sit next to each other (in one word) which would normally join together, but should not". Presentation forms such as U+FEB1 are compatibility characters: NFKC maps them to the base letter (U+0633), but plain NFC does not. Arabic and Persian are right-to-left; the Unicode Bidirectional Algorithm (UAX #9) decides the visual order of mixed text, and numbers and Latin runs inside Persian text stay left-to-right.
the same visible word "کیان" typed on two keyboards
1 Persian keyboard U+06A9 U+06CC U+0627 U+0646 (keheh, farsi yeh)
2 Arabic keyboard U+0643 U+064A U+0627 U+0646 (kaf, arabic yeh)
3 byte compare a == b ? false
4 NFC(a) == NFC(b) ? false NFKC(a) == NFKC(b) ? false (letters are not canonically equivalent)
5 after Canonical (map 064A->06CC, 0643->06A9) -> equalReal scenarios: a user registers with a name typed on an Arabic keyboard (U+064A inside it) and cannot log in with the same-looking name typed on a Persian keyboard (U+06CC); searching a product catalogue for کتاب misses titles typed with Arabic kaf; a postal-code field rejects ۱۲۳۴۵ because validation expects ASCII digits; the verb میخواهم imported from a CMS loses its ZWNJ and shows میخواهم, which is still understood but looks wrong; an invoice shows ۱۲۳ in a PDF but 123 in the database and the two never match; an RLM (U+200F) pasted from a messaging app sits invisibly at the end of a username so it is "taken" but not findable.
| Concern | Store as | Search as | Show as |
|---|---|---|---|
| Yeh and kaf | Persian U+06CC, U+06A9 | same | same |
| ZWNJ | keep | remove | keep |
| Digits in text | keep what the user typed or localize on output | ASCII | per locale (Persian or Latin digits) |
| Digits in numeric fields (phone, postal code, national ID) | ASCII | ASCII | Persian or Latin per UI |
| Harakat | keep | remove | keep |
| Tatweel | remove | remove | remove |
| Bidi marks (U+200E/F, U+202A..U+202E, U+2066..U+2069) | remove in identifiers; keep in display text only if needed | remove | n/a |
| Presentation forms | normalize to base letters | NFKC | base letters |
Fix / how to use it: one function at the boundary. Go: persian.Canonical for storage and persian.SearchKey for matching; PHP: PersianNormalizer::canonical() / searchKey(); both split the work because UAX #15 warns that "Normalization Forms KC and KD must not be blindly applied to arbitrary text", so the lossy NFKC step belongs in a separate search column, not in what the user sees.
// Package persian normalizes Persian/Arabic text. Two levels on purpose:
// Canonical is safe for storing and showing; SearchKey is lossy and for matching only.
package persian
import (
"strings"
"golang.org/x/text/unicode/norm"
)
var replacer = strings.NewReplacer(
"\u064A", "\u06CC", // Arabic yeh -> Persian yeh
"\u0649", "\u06CC", // alef maksura -> Persian yeh
"\u0643", "\u06A9", // Arabic kaf -> Persian keheh
"\u0629", "\u0647", // teh marbuta -> heh
"\u06C0", "\u0647", // heh with yeh above -> heh
"\u0640", "", // tatweel (kashida) is decoration only
"\u200F", "", // right-to-left mark
"\u200E", "", // left-to-right mark
"\u202B", "", "\u202C", "", // embedding controls
"\uFEFF", "", // BOM / zero width no-break space
)
// Digits maps Arabic-Indic (U+0660..) and Persian (U+06F0..) digits to ASCII.
// Apply it to fields that are numbers by nature (postal code, phone, national id).
func Digits(s string) string {
return strings.Map(func(r rune) rune {
switch {
case r >= '\u0660' && r <= '\u0669':
return '0' + (r - '\u0660')
case r >= '\u06F0' && r <= '\u06F9':
return '0' + (r - '\u06F0')
}
return r
}, s)
}
// isDiacritic reports Arabic harakat (U+064B..U+065F) and superscript alef.
func isDiacritic(r rune) bool {
return (r >= '\u064B' && r <= '\u065F') || r == '\u0670'
}
// Canonical is the STORAGE form: NFC (lossless for meaning), Arabic look-alike
// letters unified, decoration and invisible bidi marks removed, whitespace
// collapsed. It KEEPS ZWNJ (U+200C), digits and diacritics, because a name or
// a sentence is still the same text a human typed.
func Canonical(s string) string {
s = norm.NFC.String(s)
s = replacer.Replace(s)
return strings.Join(strings.Fields(s), " ")
}
// SearchKey is the MATCHING form: Canonical, then NFKC (folds presentation
// forms and ligatures; UAX #15 warns this is lossy), harakat removed, digits
// to ASCII, ZWNJ removed, lower-cased. Index it in its own column; never show it.
func SearchKey(s string) string {
s = norm.NFKC.String(Canonical(s))
var b strings.Builder
b.Grow(len(s))
for _, r := range s {
if isDiacritic(r) || r == '\u200C' {
continue
}
b.WriteRune(r)
}
return strings.ToLower(Digits(b.String()))
}Test and demo output on this machine (go test ./persian and go run ./demo):
ok academy/bits-bytes-text-encoding/persian 0.798s
input : [U+0643 U+0627 U+0645 U+0640 U+064A U+0627 U+0628 U+0020 U+200F U+06F1 U+06F2 U+06F3]
canonical : [U+06A9 U+0627 U+0645 U+06CC U+0627 U+0628 U+0020 U+06F1 U+06F2 U+06F3]
searchkey : [U+06A9 U+0627 U+0645 U+06CC U+0627 U+0628 U+0020 U+0031 U+0032 U+0033]
digits : "0912"<?php
declare(strict_types=1);
namespace App\Support\Text;
use Normalizer;
/**
* Normalizes Persian/Arabic text for storage, search and uniqueness checks.
* Requires ext-intl (Normalizer) and ext-mbstring.
*/
final class PersianNormalizer
{
/** Arabic look-alikes and decoration mapped to the Persian form. */
private const MAP = [
"\u{064A}" => "\u{06CC}", // Arabic yeh -> Farsi yeh
"\u{0649}" => "\u{06CC}", // alef maksura -> Farsi yeh
"\u{0643}" => "\u{06A9}", // Arabic kaf -> Keheh
"\u{0629}" => "\u{0647}", // teh marbuta -> heh
"\u{06C0}" => "\u{0647}", // heh with yeh above -> heh
"\u{0640}" => '', // tatweel
"\u{200F}" => '', // RLM
"\u{200E}" => '', // LRM
"\u{202B}" => '', // RLE
"\u{202C}" => '', // PDF
"\u{FEFF}" => '', // BOM / ZWNBSP
];
/**
* STORAGE form: NFC, look-alike letters unified, decoration and bidi marks
* removed, whitespace collapsed. Keeps ZWNJ, digits and diacritics.
*/
public static function canonical(string $text): string
{
$nfc = Normalizer::normalize($text, Normalizer::FORM_C);
if ($nfc === false) {
// Input was not valid UTF-8; refuse instead of guessing.
throw new \InvalidArgumentException('Input is not valid UTF-8');
}
$text = strtr($nfc, self::MAP);
$text = preg_replace('/\s+/u', ' ', $text) ?? $text;
return trim($text);
}
/**
* MATCHING form (lossy): canonical + NFKC + harakat removed + ASCII digits
* + ZWNJ removed + lower-case. UAX #15 warns NFKC must not be applied blindly,
* so keep this in a separate column and never display it.
*/
public static function searchKey(string $text): string
{
$key = Normalizer::normalize(self::canonical($text), Normalizer::FORM_KC);
if ($key === false) {
throw new \InvalidArgumentException('Input is not valid UTF-8');
}
// Harakat U+064B..U+065F, superscript alef U+0670, ZWNJ U+200C.
$key = preg_replace('/[\x{064B}-\x{065F}\x{0670}\x{200C}]/u', '', $key) ?? $key;
return mb_strtolower(self::digits($key), 'UTF-8');
}
/** Persian (U+06F0..) and Arabic-Indic (U+0660..) digits to ASCII. */
public static function digits(string $text): string
{
static $map = null;
if ($map === null) {
$map = [];
for ($i = 0; $i <= 9; $i++) {
$map[mb_chr(0x06F0 + $i, 'UTF-8')] = (string) $i;
$map[mb_chr(0x0660 + $i, 'UTF-8')] = (string) $i;
}
}
return strtr($text, $map);
}
}Normalization: NFC, NFD, NFKC, NFKD Must-know
In plain words: Unicode often has two ways to write the same visible text, such as é as one code point or as e plus an accent. Normalization rewrites both to one chosen form so equal-looking text compares equal.
Common misunderstanding: "Normalization fixes all look-alikes." It only unifies text that Unicode defines as equivalent. It does not map Arabic yeh to Persian yeh, Cyrillic а to Latin a, or ß to ss; those need your own mapping, confusable detection or case folding.
Definition: UAX #15 defines two equivalences. Canonical equivalence is "a fundamental equivalency between characters or sequences of characters which represent the same abstract character, and which when correctly displayed should always have the same visual appearance and behavior". Compatibility equivalence also folds formatting variants (ligature fi to fi, circled ① to 1, fullwidth forms, Arabic presentation forms). The four forms: NFD (canonical decomposition), NFC (decomposition then canonical composition), NFKD (compatibility decomposition), NFKC (compatibility decomposition then composition). NFC is the web's default; NFKC and NFKD are lossy.
"café" in the two canonical forms
1 NFC 63 61 66 c3 a9 4 code points (é = U+00E9)
2 NFD 63 61 66 65 cc 81 5 code points (e + U+0301 COMBINING ACUTE ACCENT)
3 a == b (bytes) false
4 NFC(a) == NFC(b) true
5 NFC("fi") = "fi" NFKC("fi") = "fi" NFKC("①") = "1" NFKC(U+FE8F) = U+0628Real scenarios: macOS's HFS+ historically stored file names in a decomposed form (NFD-like), so a file named café.txt created on a Mac can fail to match the NFC name in Git, S3 or a database on Linux; a username café registered twice (once NFC, once NFD) passes a uniqueness check; a search for é misses text pasted with e + accent; two services hash the same display name and get different digests; Safari and Chrome send text in the form typed.
| Form | Does | Lossy? | Use it for |
|---|---|---|---|
| NFC | Compose where possible | No (canonical) | Storage, interchange, comparison of canonical equivalents |
| NFD | Fully decompose | No (canonical) | Stripping accents (decompose, then drop Mn marks) |
| NFKC | Compose and fold compatibility variants | Yes | Search keys, identifiers, usernames (with care) |
| NFKD | Decompose and fold compatibility variants | Yes | Aggressive ASCII-folding pipelines |
| When to normalize | Form | Reason |
|---|---|---|
| At the input boundary, user-visible text | NFC | Same bytes for the same text; no loss |
| Usernames, handles, emails local-part | NFKC plus case folding plus your own rules | Block look-alikes and width tricks; follow your identity policy |
| File names across OSes | NFC at your boundary (compare in NFC) | macOS and Linux disagree on forms |
| Search index and query | NFKC plus case folding plus Persian map | Same transformation on both sides |
| Cryptographic input (hashes, signatures, passwords) | Decide once and document; passwords are typically NFKC per NIST SP 800-63B | The bytes you hash must be the bytes you verify |
Fix / how to use it: Go: norm.NFC.String(s), norm.NFC.IsNormalString(s) (fast check), norm.NFC.Bytes(b) from golang.org/x/text/unicode/norm; PHP: Normalizer::normalize($s, Normalizer::FORM_C) and Normalizer::isNormalized (ext-intl); PostgreSQL 13+: normalize(text, NFC) and IS NFC NORMALIZED; MySQL has no built-in normalize function, so normalize in the application.
// Unicode normalization forms and grapheme clusters.
package main
import (
"fmt"
"unicode/utf8"
"github.com/rivo/uniseg"
"golang.org/x/text/unicode/norm"
)
func main() {
nfc := "caf\u00E9" // \u00E9 as one code point
nfd := "cafe\u0301" // e + combining acute
fmt.Println("looks equal :", nfc, nfd)
fmt.Println("== (bytes) :", nfc == nfd)
fmt.Printf("NFC bytes : % x (%d runes)\n", []byte(nfc), utf8.RuneCountInString(nfc))
fmt.Printf("NFD bytes : % x (%d runes)\n", []byte(nfd), utf8.RuneCountInString(nfd))
fmt.Println("NFC(a)==NFC(b) :", norm.NFC.String(nfc) == norm.NFC.String(nfd))
fmt.Println("IsNormalString :", norm.NFC.IsNormalString(nfd), norm.NFD.IsNormalString(nfd))
// Compatibility forms fold presentation variants.
fmt.Printf("NFKC(\uFB01) : %q\n", norm.NFKC.String("\uFB01"))
fmt.Printf("NFKC(\u2460) : %q\n", norm.NFKC.String("\u2460"))
fmt.Printf("NFC(\uFB01) : %q (unchanged)\n", norm.NFC.String("\uFB01"))
// Arabic presentation form (isolated beh) folds to the base letter.
fmt.Printf("NFKC(U+FE8F) : %U\n", []rune(norm.NFKC.String("\uFE8F")))
// Grapheme clusters: what a user counts as one character.
for _, s := range []string{"\u00E9", "e\u0301", "👨\u200D👩\u200D👧", "🇮🇷", "👍🏽", "می\u200Cخواهم"} {
fmt.Printf("%-10q bytes=%-2d runes=%-2d graphemes=%d\n",
s, len(s), utf8.RuneCountInString(s), uniseg.GraphemeClusterCount(s))
}
}Real output of go run ./norm (first part):
looks equal : café café
== (bytes) : false
NFC bytes : 63 61 66 c3 a9 (4 runes)
NFD bytes : 63 61 66 65 cc 81 (5 runes)
NFC(a)==NFC(b) : true
IsNormalString : false true
NFKC(fi) : "fi"
NFKC(①) : "1"
NFC(fi) : "fi" (unchanged)
NFKC(U+FE8F) : [U+0628]Collation and case folding Important
In plain words: Sorting and "equal ignoring case" depend on language. Where ä sorts, whether ß equals ss, and what the capital of i is, all vary by locale. A collation is a database's rulebook for comparing and sorting strings.
Common misunderstanding: "LOWER(a) = LOWER(b) is case-insensitive comparison." It is wrong for Turkish (I lowercases to dotless ı in the Turkish locale), for German (ß uppercases to SS), and for any text that is not normalized. Use case folding (a comparison transform) in the right locale, or a collation that does it.
Definition: case mapping (upper, lower, title) changes display; case folding (casefold) is for caseless matching. The Unicode FAQ says "Some case mappings depend on language or locale", and SpecialCasing.txt lists Turkish and Lithuanian rules (for example 0130; 0069 0307; 0130; 0130; for U+0130 LATIN CAPITAL LETTER I WITH DOT ABOVE). A collation defines comparison and ordering; PostgreSQL's manual distinguishes deterministic collations (equal only if bytes are equal) from nondeterministic ones, where "Nondeterministic comparison may determine strings to be equal even if they consist of different bytes".
case and locale surprises, Python 3 on this machine
1 'ß'.upper() -> 'SS'
2 'ß'.casefold() -> 'ss' 'STRASSE'.casefold() == 'straße'.casefold() -> True
3 'I'.lower() -> 'i' (Turkish locale would say 'ı', U+0131)
4 'İ'.lower() (UTF-8 hex) -> 69 cc 87 = 'i' + COMBINING DOT ABOVE (U+0307)Real scenarios: a Turkish customer's INFO becomes ınfo after a locale-aware lowercase; a German email domain compare fails because of ß; a MySQL utf8mb4_unicode_ci unique index treats a and á as equal while PostgreSQL's default does not; a PostgreSQL index built under one glibc version returns wrong order after an OS upgrade changes collation rules; sorting Persian names with the C collation gives code point order, not alphabetical order.
| Engine | Default comparison | Case-insensitive options | Notes |
|---|---|---|---|
| PostgreSQL | Deterministic collation from the database locale (libc or icu provider) | citext extension, lower() indexes, ICU nondeterministic collation (deterministic = false) | Collation changes after OS or ICU upgrades can corrupt indexes: REINDEX and pg_collation_actual_version |
| MySQL 8.4 | utf8mb4_0900_ai_ci (accent- and case-insensitive) | _as_cs, _bin, utf8mb4_unicode_ci | _ci collations make UNIQUE match A and a; _bin compares bytes |
| MariaDB | Depends on the version | _ci/_cs variants | Check SHOW COLLATION and the server default |
| SQL Server | database collation (for example SQL_Latin1_General_CP1_CI_AS) | _CS, _CI, _AS, _AI, _UTF8 | Case and accent sensitivity are part of the collation name |
| Oracle | NLS_SORT, NLS_COMP | BINARY_CI, GENERIC_M_CI | Linguistic sort is optional |
| SQLite | BINARY | NOCASE (ASCII only) | Full Unicode needs the ICU extension |
| Go | byte order for < and == | strings.EqualFold; golang.org/x/text/collate for locale order | x/text/cases for locale-aware casing |
| PHP | byte order for < and == | mb_strtolower, Collator (ext-intl), mb_convert_case | strcasecmp is ASCII-only |
The two most important MySQL facts, from the MySQL 8.4 manual: "The utf8mb3 character set is deprecated" and utf8 is its alias, so "all new applications should use utf8mb4", which "requires a maximum of four bytes per multibyte character" and supports emoji and other supplementary characters. Collations and database-specific index behaviour are owned by the database path; see Schema Design, Normalization & Data Types and Indexing.
Fix / how to use it: pick a collation deliberately at schema creation, test it with your own strings (Persian, accents, emoji), and for uniqueness build a separate normalized key column rather than trusting a collation. Go: strings.EqualFold for simple folding; cases.Fold() from golang.org/x/text/cases. PHP: mb_strtolower($s, 'UTF-8'); for Turkish use Collator/transliterator. Laravel migrations: $table->charset('utf8mb4'); $table->collation('utf8mb4_unicode_ci'); as the Laravel docs show.
String length pitfalls Must-know
In plain words: "Length" can mean bytes, code points or visible characters, and different functions pick different answers for the same word.
Common misunderstanding: "VARCHAR(255) holds 255 bytes (or 255 characters) everywhere." It depends on the engine, and sometimes on the column's character set.
Definition and per-engine semantics:
| Product | n in VARCHAR(n) counts | Statement from the vendor docs | Gotcha |
|---|---|---|---|
| PostgreSQL | characters | "Both of these types can store strings up to n characters (not bytes) in length" | Over-length raises an error unless the excess is spaces; explicit cast truncates silently |
| MySQL (InnoDB) | characters | CHAR(30) "can hold up to 30 characters" | A row is limited to 65,535 bytes, so many VARCHAR(255) utf8mb4 columns can overflow the row size; index key limits are in bytes |
| Oracle | bytes by default (BYTE) or characters (CHAR) | "The qualifier BYTE denotes byte length semantics while the qualifier CHAR denotes character length semantics" | VARCHAR2(10) may hold 5 Persian letters; write VARCHAR2(10 CHAR) |
| SQL Server | varchar(n) bytes, nvarchar(n) byte-pairs | "n never defines numbers of characters" for nvarchar(n); characters above U+FFFF use two byte-pairs | A single emoji can need 2 of the 4,000 pairs |
| SQLite | not enforced | Declared lengths are ignored (type affinity) | The app must enforce limits |
| MongoDB | no declared length | BSON strings are UTF-8 with a length prefix | The document limit is in bytes (16 MiB) |
| Operation | Go | PHP | PostgreSQL | MySQL | JavaScript |
|---|---|---|---|---|---|
| Bytes | len(s) | strlen($s) | octet_length(s) | LENGTH(s) | new TextEncoder().encode(s).length |
| Code points | utf8.RuneCountInString(s) | mb_strlen($s, 'UTF-8') | length(s), char_length(s) | CHAR_LENGTH(s) | [...s].length |
| UTF-16 units | len(utf16.Encode([]rune(s))) | strlen(mb_convert_encoding($s, 'UTF-16LE', 'UTF-8')) / 2 | n/a | n/a | s.length |
| Graphemes | uniseg.GraphemeClusterCount(s) | grapheme_strlen($s) | n/a | n/a | Intl.Segmenter |
truncating "سلام" (8 bytes) to 3 bytes
1 s[:3] -> d8 b3 d9 (cut inside the second letter)
2 utf8.ValidString -> false
3 printed -> "س\xd9" (invalid byte)
4 safe truncate -> back up while !utf8.RuneStart(s[n]) -> "س" (2 bytes)
5 PHP substr($s, 0, 3) -> same broken bytes; mb_strcut($s, 0, 3, 'UTF-8') -> "س"Real scenarios: a substr($name, 0, 20) in PHP leaves half a Persian letter and a later json_encode returns false with "Malformed UTF-8 characters"; a Go service that does s[:n] for a preview writes an invalid UTF-8 byte that PostgreSQL rejects with invalid byte sequence for encoding "UTF8"; a database column VARCHAR(50) in Oracle rejects a 30-letter Persian name because it is 60 bytes.
Fix / how to use it: Go: truncate with a rune-boundary loop (see truncateBytes in runes/main.go) or convert to []rune; PHP: mb_substr (code points) or mb_strcut (byte limit that respects characters); Laravel: Str::limit() and Str::length() are multibyte-aware but not grapheme-aware, and the validation max:n rule counts characters. Size limits in storage should be bytes, user-facing limits should be graphemes.
// Bytes, runes and UTF-16 units for the same Persian string.
package main
import (
"fmt"
"strings"
"unicode/utf16"
"unicode/utf8"
)
func main() {
s := "سلام" // 4 code points, 8 bytes in UTF-8
fmt.Println("len (bytes) :", len(s))
fmt.Println("RuneCountInString :", utf8.RuneCountInString(s))
fmt.Println("[]rune length :", len([]rune(s)))
fmt.Printf("UTF-8 hex : % x\n", []byte(s))
u16 := utf16.Encode([]rune(s))
fmt.Printf("UTF-16 units : %04x\n", u16)
// Iterating a string yields runes with their BYTE offsets.
for i, r := range s {
fmt.Printf(" offset %d U+%04X %q %d bytes\n", i, r, r, utf8.RuneLen(r))
}
// Slicing by bytes can cut a code point in half.
cut := s[:3]
fmt.Printf("s[:3] : % x valid UTF-8? %v\n", []byte(cut), utf8.ValidString(cut))
fmt.Printf("printed : %q\n", cut)
// Safe truncation: back up to a rune boundary.
fmt.Printf("safe truncate(3) : %q\n", truncateBytes(s, 3))
// Emoji: one user-perceived character, many code points.
family := "👨\u200D👩\u200D👧"
fmt.Println("family emoji bytes :", len(family), " runes:", utf8.RuneCountInString(family))
for _, r := range family {
fmt.Printf(" U+%04X\n", r)
}
// Supplementary plane: surrogate pair in UTF-16.
pair := utf16.Encode([]rune("😀"))
fmt.Printf("😀 in UTF-16 : %04x (surrogate pair)\n", pair)
// Invalid bytes become U+FFFD when ranging.
bad := string([]byte{0x61, 0xC0, 0x80, 0xFF, 0x62})
for _, r := range bad {
fmt.Printf("%U ", r)
}
fmt.Println()
fmt.Printf("ToValidUTF8 : %q\n", strings.ToValidUTF8(bad, "\uFFFD"))
}
// truncateBytes returns at most n bytes without splitting a code point.
func truncateBytes(s string, n int) string {
if len(s) <= n {
return s
}
for n > 0 && !utf8.RuneStart(s[n]) {
n--
}
return s[:n]
}Real output of go run ./runes:
len (bytes) : 8
RuneCountInString : 4
[]rune length : 4
UTF-8 hex : d8 b3 d9 84 d8 a7 d9 85
UTF-16 units : [0633 0644 0627 0645]
offset 0 U+0633 'س' 2 bytes
offset 2 U+0644 'ل' 2 bytes
offset 4 U+0627 'ا' 2 bytes
offset 6 U+0645 'م' 2 bytes
s[:3] : d8 b3 d9 valid UTF-8? false
printed : "س\xd9"
safe truncate(3) : "س"
family emoji bytes : 18 runes: 5
U+1F468
U+200D
U+1F469
U+200D
U+1F467
😀 in UTF-16 : [d83d de00] (surrogate pair)
U+0061 U+FFFD U+FFFD U+FFFD U+0062
ToValidUTF8 : "a�b"Encoding at every boundary Must-know
In plain words: Text crosses many borders: browser to server, server to database, program to file, program to terminal. Every border has its own encoding setting, and the weakest one decides what survives.
Common misunderstanding: "My code is UTF-8, so everything is UTF-8." Your source file, the HTTP header, the database connection, the column, the terminal and the file you write can each use a different encoding. A pipeline is only as correct as its least-configured hop.
Definition: list every hop and make each one explicit. JSON is the easy one: RFC 8259 says "JSON text exchanged between systems that are not part of a closed ecosystem MUST be encoded using UTF-8", so JSON APIs need no charset negotiation.
a Persian name travelling through a web request
1 browser form -> POST body, percent-encoded UTF-8 (%D8%B3%D9%84%D8%A7%D9%85)
2 HTTP header -> Content-Type: application/x-www-form-urlencoded; charset=UTF-8
3 Laravel/PHP -> $request->input('name') is a UTF-8 byte string
4 DB connection -> charset utf8mb4 (MySQL) / client_encoding UTF8 (PostgreSQL)
5 column -> utf8mb4 / database ENCODING 'UTF8'
6 response -> Content-Type: application/json (UTF-8 implied), HTML: <meta charset="utf-8">Real scenarios: a Laravel app on MySQL with charset => utf8 (not utf8mb4) loses emoji at insert time; a PostgreSQL connection with client_encoding = LATIN1 makes the server translate and reject Persian with character with byte sequence ... in encoding "UTF8" has no equivalent in encoding "LATIN1"; a Windows terminal in a legacy code page prints ? although the data is correct; a CSV opened in Excel shows mojibake unless it starts with a BOM; a URL with raw Persian characters is re-encoded differently by two proxies.
| Boundary | How the encoding is declared | Default if you say nothing | Set it to |
|---|---|---|---|
| HTTP response | Content-Type: text/html; charset=utf-8 | Browsers guess (WHATWG: windows-1252 for many legacy labels) | charset=utf-8 and <meta charset="utf-8"> |
| HTTP form post | accept-charset, Content-Type charset | Page encoding | UTF-8 pages and forms |
| JSON | none (RFC 8259: UTF-8) | UTF-8 | UTF-8, no BOM |
| URLs and query strings | percent-encoded UTF-8 bytes (RFC 3986 leaves the choice to the scheme; WHATWG URL uses UTF-8) | n/a | Percent-encode UTF-8; see Binary-to-Text Encoding |
| PostgreSQL | database ENCODING; session client_encoding | Database encoding; client default from the server or driver | UTF8 database; SET client_encoding TO 'UTF8' or ?client_encoding=UTF8 |
| MySQL | server character_set_server; connection SET NAMES utf8mb4 | utf8mb4 in MySQL 8.0+, latin1 in 5.7 | utf8mb4 everywhere; Laravel 'charset' => 'utf8mb4' in config/database.php |
| Files | BOM, # coding:, file metadata, or nothing | Platform dependent (locale) | UTF-8 without BOM, except Excel CSV (UTF-8 with BOM) |
| Terminal | locale (LANG, LC_ALL), terminal setting | C/POSIX or system locale | LANG=C.UTF-8 or en_US.UTF-8; Windows chcp 65001 |
| Source code | Go: UTF-8 required; PHP: bytes as written | n/a | Save as UTF-8 |
Content-Type charset and transfer encoding | us-ascii | UTF-8, quoted-printable or base64 body; RFC 2047 for headers | |
| Logs | no declaration | bytes as written | UTF-8; escape control characters |
Real output on this machine: locale reports LANG="C.UTF-8", and the header of a public site shows the declared encoding:
$ curl -sI https://example.com | grep -i content-type
content-type: text/html; charset=utf-8Fix / how to use it: Go: HTTP handlers set w.Header().Set("Content-Type", "application/json; charset=utf-8") (the charset on JSON is optional) and database/sql drivers take the encoding in the DSN (pgx: client_encoding is always UTF8; go-sql-driver/mysql: charset=utf8mb4). Laravel: config/database.php MySQL entry 'charset' => 'utf8mb4', 'collation' => 'utf8mb4_unicode_ci'; PostgreSQL entry 'charset' => 'utf8'; Blade pages emit <meta charset="utf-8">; response()->json() emits UTF-8 and, by default, escapes non-ASCII as \uXXXX unless you pass JSON_UNESCAPED_UNICODE.
Detecting and converting encodings Important
In plain words: If you do not know a file's encoding you can only guess, and tools such as file and chardet guess from statistics. If you know it, you convert with iconv or a library.
Common misunderstanding: "Detection is reliable." For short strings it is not: caf\xe9 is valid Latin-1 and also an invalid UTF-8 prefix, but a short Persian string in Windows-1256 can look like valid Latin-1 or valid UTF-8. Detection gives a probability, not a fact.
Definition: a valid UTF-8 check is a strong signal (random non-UTF-8 text almost never passes), so detect in this order: BOM, then "is it valid UTF-8?", then a statistical guess among the legacy encodings you actually expect (for Persian files: Windows-1256, ISO 8859-6, UTF-16LE).
a file of unknown origin
1 head -c 4 | xxd -> ff fe .. -> UTF-16LE with BOM (or ef bb bf -> UTF-8 with BOM)
2 iconv -f UTF-8 -t UTF-8 file > /dev/null -> exit 0 -> valid UTF-8 ; exit 1 "Illegal byte sequence" -> not UTF-8
3 file -I file -> "charset=iso-8859-1" is a guess, not proof
4 if still unknown, try the expected legacy charset and eyeball the result (Windows-1256 for old Persian)Real commands and results on this machine:
$ printf '\xc0\x80' | iconv -f UTF-8 -t UTF-16LE
iconv: iconv(): Illegal byte sequence (exit 1: the overlong form is rejected)
$ printf 'café\n' | iconv -f UTF-8 -t ASCII
iconv: iconv(): Illegal byte sequence (strict: cannot represent é)
$ printf 'café\n' | iconv -f UTF-8 -t ASCII//TRANSLIT
iconv: warning: invalid characters: 1
caf'e (macOS prints caf'e; glibc prints cafe)
$ printf 'caf\xc3' | iconv -f UTF-8 -t UTF-16LE
c a f iconv: unexpected end of file; the last character is incomplete.| Tool | Detect | Convert | Notes |
|---|---|---|---|
file -I (libmagic) | statistical guess, prints charset= | no | Treat as a hint |
iconv -f A -t B | no (validates as a side effect) | yes, with //TRANSLIT, //IGNORE suffixes | //TRANSLIT output differs between glibc and macOS |
uchardet, chardetng, Python charset-normalizer | yes, probabilistic | no | Use only when you cannot ask the producer |
recode, dos2unix, unix2dos | no | line endings and code pages | dos2unix fixes CRLF |
Go golang.org/x/text/encoding (charmap, unicode, simplifiedchinese, htmlindex) | htmlindex.Name resolves labels per WHATWG | NewDecoder().String(s) / NewEncoder() | Use transform.NewReader for streams |
Go utf8 package | utf8.Valid, utf8.ValidString | no | Validate before storing |
| PHP mbstring | mb_detect_encoding($s, ['UTF-8','Windows-1256'], true) (strict) | mb_convert_encoding($s, 'UTF-8', 'Windows-1256') | Always pass an explicit candidate list and true for strict |
| PHP iconv | no | iconv('Windows-1256', 'UTF-8//IGNORE', $s) | //IGNORE silently drops bytes |
| PostgreSQL | pg_encoding_to_char, convert_from(bytea, 'LATIN1') | convert_to(text, 'WIN1256'), convert(bytea, 'WIN1256', 'UTF8') | Server converts to client encoding automatically |
| MySQL | CONVERT(col USING utf8mb4), HEX(col) | ALTER TABLE ... CONVERT TO CHARACTER SET utf8mb4 | A binary CAST(col AS BINARY) round trip repairs double encoding |
Fix / how to use it: convert once at ingest, not at read time; keep the original bytes; log the source encoding. Go uses charmap.Windows1256.NewDecoder().String(s) (shown in convert/main.go); PHP uses mb_convert_encoding (shown in Binary.php).
Reading hex dumps Must-know
In plain words: A hex dump prints each byte as two hex digits, with an ASCII side column. It is the only view that does not hide encoding problems.
Common misunderstanding: "My editor shows the text fine, so the bytes are fine." Editors repair, guess and hide: they drop BOMs, render ZWNJ as nothing, show NFC and NFD identically and normalize line endings. Only the bytes tell the truth.
Definition: xxd file (offset, 8 groups of 2 bytes, ASCII) and hexdump -C file (offset, 16 single bytes, ASCII between bars) print bytes in file order. xxd -b prints bits. xxd -r reverses a dump. od -An -tx1 prints bytes without offsets. For network captures tcpdump -X and Wireshark use the same layout.
Real output, with annotations:
$ echo -n "سلام میخواهم" | hexdump -C
00000000 d8 b3 d9 84 d8 a7 d9 85 20 d9 85 db 8c e2 80 8c |........ .......|
00000010 d8 ae d9 88 d8 a7 d9 87 d9 85 |..........|
0000001a
d8 b3 = U+0633 س d9 84 = U+0644 ل d8 a7 = U+0627 ا d9 85 = U+0645 م
20 = space d9 85 = U+0645 م db 8c = U+06CC ی e2 80 8c = U+200C ZWNJ (invisible, 3 bytes)
$ printf '😀' | xxd -b
00000000: 11110000 10011111 10011000 10000000 ....
$ printf '\xef\xbb\xbfhello\n' | xxd
00000000: efbb bf68 656c 6c6f 0a ...hello. (BOM then text)| What you see in the dump | It means |
|---|---|
ef bb bf at offset 0 | UTF-8 BOM |
ff fe or fe ff at offset 0 | UTF-16 BOM (little / big endian) |
Many 00 bytes between ASCII bytes | UTF-16 or UTF-32 |
c3 a9 | é in NFC; 65 cc 81 is e plus U+0301 (NFD) |
e2 80 8c, e2 80 8d, e2 80 8f | ZWNJ, ZWJ, RLM: invisible characters inside the text |
c3 83 c2 a9 | double-encoded é (mojibake) |
d8 / d9 / da / db lead bytes | Arabic-script letters in UTF-8 (U+0600-U+06FF) |
0d 0a | CRLF line ending |
ed a0 .. to ed bf .. | encoded surrogate: invalid UTF-8 |
f0 9f start | an emoji or other supplementary-plane character |
Fix / how to use it: make "dump the bytes" the first debugging step: xxd for files, tcpdump -A -X for packets, SELECT encode(convert_to(col, 'UTF8'), 'hex') in PostgreSQL, SELECT HEX(col) in MySQL, bin2hex($s) in PHP, fmt.Printf("% x", []byte(s)) in Go.
Per-tool and per-product behaviour
What each platform does with text, in one table.
| Product | Native string model | Default encoding | Invalid UTF-8 handling | Normalization built in? |
|---|---|---|---|---|
| Go | byte string, UTF-8 by convention; rune is a code point | UTF-8 | Accepts any bytes; range yields U+FFFD; utf8.ValidString checks | No; golang.org/x/text/unicode/norm |
| PHP | byte string, no encoding attached | Bytes as written; default_charset ini (UTF-8 since 5.6) | mb_check_encoding; json_encode fails with error 5 (JSON_ERROR_UTF8) | Normalizer (ext-intl) |
| Laravel 13 | Illuminate string helpers use mbstring | UTF-8 | Validation rule string accepts bytes; use custom rule or middleware | No (write a middleware) |
| JavaScript | UTF-16 code units | UTF-16 | Lone surrogates allowed; TextDecoder replaces with U+FFFD | String.prototype.normalize |
| Python 3 | code point sequence | UTF-8 source; str is Unicode | bytes.decode raises UnicodeDecodeError | unicodedata.normalize |
| PostgreSQL | text in the database encoding | UTF8 recommended | Error 22021 invalid byte sequence for encoding "UTF8" | normalize() since 13 |
| MySQL 8.4 | by charset | utf8mb4 (8.0+) | Strict mode: error 1366 Incorrect string value; non-strict truncates | No |
| SQL Server | nvarchar UTF-16; varchar by collation | collation code page; UTF-8 collations in 2019+ | n/a | No |
| SQLite | UTF-8 (or UTF-16) | UTF-8 | Stores bytes; functions assume UTF-8 | No |
| Redis | binary-safe strings | n/a | none | No |
| Elasticsearch | JSON UTF-8; analyzers on tokens | UTF-8 | rejects invalid JSON | ICU analysis plugin (icu_normalizer, icu_folding) |
Languages for the same operations.
| Operation | Go | PHP / Laravel |
|---|---|---|
| Iterate code points | for i, r := range s | mb_str_split($s) |
| Count code points | utf8.RuneCountInString(s) | mb_strlen($s, 'UTF-8'), Str::length($s) |
| Substring by code points | string([]rune(s)[a:b]) | mb_substr($s, $a, $n, 'UTF-8'), Str::substr |
| Validate UTF-8 | utf8.ValidString(s) | mb_check_encoding($s, 'UTF-8') |
| Replace invalid bytes | strings.ToValidUTF8(s, string(utf8.RuneError)) | mb_convert_encoding($s, 'UTF-8', 'UTF-8') or iconv('UTF-8', 'UTF-8//IGNORE', $s) |
| Normalize NFC | norm.NFC.String(s) | Normalizer::normalize($s, Normalizer::FORM_C) |
| Lower-case | strings.ToLower(s); cases.Lower(language.Turkish) | mb_strtolower($s, 'UTF-8'), Str::lower($s) |
| Byte order | binary.BigEndian / LittleEndian | pack('N') / pack('V') |
| Transliterate to ASCII | golang.org/x/text/transform with norm.NFD and a filter | Str::ascii($s), iconv('UTF-8', 'ASCII//TRANSLIT', $s), transliterator_transliterate('Any-Latin; Latin-ASCII', $s) |
| Graphemes | uniseg | grapheme_strlen |
Databases for string rules.
| Product | UTF-8 storage type | Max index key / length notes | Recommended collation approach | length function |
|---|---|---|---|---|
| PostgreSQL | text, varchar(n) in a UTF8 database | varchar(n) n up to 10,485,760 characters; btree entries are limited by page size | ICU collation or citext or normalized key column | length, octet_length |
| MySQL / InnoDB | utf8mb4 | Row size 65,535 bytes; index prefix 3072 bytes (DYNAMIC) | utf8mb4_0900_ai_ci or utf8mb4_unicode_ci; _bin for exact | CHAR_LENGTH, LENGTH |
| MariaDB | utf8mb4 | similar | choose by version | same |
| SQL Server | nvarchar or UTF-8 varchar collation | 900-byte clustered, 1700-byte nonclustered index keys | Latin1_General_100_CI_AS_SC_UTF8 | LEN (characters, trims trailing spaces), DATALENGTH bytes |
| Oracle | NVARCHAR2 or AL32UTF8 database | VARCHAR2 max 4000 bytes (32767 extended) | NLS_SORT | LENGTH, LENGTHB |
| SQLite | TEXT | none enforced | COLLATE NOCASE is ASCII-only | length() characters, length(CAST(x AS BLOB)) bytes |
| MongoDB | BSON string, UTF-8 | 16 MiB document | collation option per collection/index (ICU) | $strLenCP, $strLenBytes |
| CockroachDB | UTF-8 STRING | like PostgreSQL | ICU collation via COLLATE | length, octet_length |
| Redis | binary-safe | 512 MB value | n/a | STRLEN bytes |
Mechanics
The UTF-8 decoder, step by step Important
- Read byte
b0. Ifb0 < 0x80, emit it (1 byte). - If
0xC2 <= b0 <= 0xDF, expect 1 continuation byte; if0xE0 <= b0 <= 0xEF, 2; if0xF0 <= b0 <= 0xF4, 3. Bytes0x80-0xBF(stray continuation),0xC0,0xC1and0xF5-0xFFnever start a sequence. - Each continuation byte must be
10xxxxxx(0x80-0xBF), with tighter bounds on the second byte forE0(A0-BF),ED(80-9F, to exclude surrogates),F0(90-BF) andF4(80-8F, to stay under U+10FFFF). - Combine payload bits; the result must be at least the minimum for its length (that rejects overlong forms such as
C0 80). - On any failure, a lenient decoder emits U+FFFD and resynchronises at the next byte that is not a continuation byte; a strict decoder raises an error. The WHATWG Encoding Standard prescribes the replacement behaviour for browsers.
a decoder meeting bad input: bytes 61 C0 80 FF 62
1 61 -> 'a'
2 C0 -> never valid as a lead byte -> U+FFFD (Go range yields three U+FFFD, one per invalid byte)
3 80 -> stray continuation -> U+FFFD
4 FF -> never valid -> U+FFFD
5 62 -> 'b'
6 strings.ToValidUTF8(s, string(utf8.RuneError)) collapses the run into a single U+FFFD: "a" + U+FFFD + "b"Surrogate pairs, the arithmetic Good to know
Encode: v = cp - 0x10000; high = 0xD800 + (v >> 10); low = 0xDC00 + (v & 0x3FF). Decode: cp = 0x10000 + ((high - 0xD800) << 10) + (low - 0xDC00). For U+1F600: v = 0xF600, v >> 10 = 0x3D, v & 0x3FF = 0x200, so D83D DE00, which matches the Go and Python outputs on this page. A lone high or low surrogate is ill-formed; JavaScript tolerates it, Go replaces it with U+FFFD, UTF-8 forbids it.
Two's complement, quickly Good to know
For n bits, -x is (2^n - x), or invert and add 1. Example with 8 bits: 5 is 0000 0101, invert 1111 1010, add 1 1111 1011 = 0xFB = -5. Adding 5 to it gives 1 0000 0000; the ninth bit is discarded, leaving 0. That discarded carry is the wrap-around the Go spec describes.
Error messages you will meet, verbatim Must-know
| Where | Message or code | Meaning | Fix |
|---|---|---|---|
| PostgreSQL | ERROR: invalid byte sequence for encoding "UTF8": 0xe9 0x0a (SQLSTATE 22021) | Input is not valid UTF-8 (often Latin-1) | Convert at ingest; fix client encoding |
| PostgreSQL | character with byte sequence 0xd8 0xb3 in encoding "UTF8" has no equivalent in encoding "LATIN1" (22P05) | Server encoding or client_encoding cannot hold the character | Use UTF8 everywhere |
| PostgreSQL | invalid byte sequence for encoding "UTF8": 0x00 | NUL bytes are not allowed in text | Strip \0 or use bytea |
| MySQL | ERROR 1366 (HY000): Incorrect string value: '\xF0\x9F\x98\x80' for column 'name' at row 1 | Column charset cannot store the character (usually utf8mb3) | Convert column to utf8mb4 |
| MySQL | ERROR 1300 (HY000): Invalid utf8mb4 character string | Invalid bytes in a literal | Validate input |
| MySQL | ERROR 1267 Illegal mix of collations | Comparing columns or literals with different collations | Align collations or use COLLATE |
| MySQL | ERROR 1264 Out of range value for column | Numeric overflow in strict mode | Widen the type |
| PostgreSQL | ERROR: integer out of range (22003) | Arithmetic overflow | bigint or numeric |
| iconv | iconv: iconv(): Illegal byte sequence | Input invalid for the source charset | Fix the source charset label |
| iconv | iconv: unexpected end of file; the last character is incomplete. | Truncated multi-byte character | Find where the stream was cut |
| PHP | json_encode returns false, json_last_error_msg() is Malformed UTF-8 characters, possibly incorrectly encoded | Invalid UTF-8 in a string | mb_convert_encoding, JSON_INVALID_UTF8_SUBSTITUTE |
| PHP | mb_substr(): ... no error; substr silently cuts bytes | Byte function on UTF-8 | Use mb_* |
| Go | invalid UTF-8 is not an error; json.Marshal replaces invalid bytes with U+FFFD | Lenient by design | Validate with utf8.ValidString where it matters |
| Go | x/text encoder: encoding: rune not supported by encoding. | Target charset cannot represent the rune | Use encoding.ReplaceUnsupported or UTF-8 |
| HTTP | 406, 415 for charset or content negotiation | Rare for UTF-8; check Accept-Charset | Serve UTF-8 |
Solving the classic problems
| Problem | Typical symptom | Solution | How | Advantage | Cost or limitation |
|---|---|---|---|---|---|
| Double encoding / mojibake | é, سلام | Fix at the producer; repair stored data once | Decode with the wrong charset then re-decode as UTF-8 | Data restored when no byte was lost | Impossible if a lossy conversion (?) happened |
| Truncation mid-code-point | \xd9 at the end, Malformed UTF-8 | Truncate at a rune boundary | utf8.RuneStart loop (Go), mb_strcut (PHP) | Always-valid UTF-8 | A display limit should still use graphemes |
| Mixed yeh/kaf breaks search | کتاب finds nothing | Search key column with a Persian map | PersianNormalizer::searchKey, persian.SearchKey, translate() in SQL | Matches whichever keyboard typed it | One more column to keep in sync |
| Look-alike or duplicate usernames | Two accounts that look the same | NFKC + case fold + ASCII or script allow-list; unique index on the key | Canonicalize then validate | Blocks confusables | Policy decisions (which scripts) |
| Invisible ZWNJ/RLM in IDs | "Username taken" but not findable | Reject Cf characters in identifiers; strip in search keys | preg_match('/\p{Cf}/u') / unicode.Is(unicode.Cf, r) | Predictable identifiers | Legitimate ZWNJ stays allowed in names |
| NFC vs NFD file names | café.txt exists but is not found | Normalize names to NFC at your boundary | norm.NFC.String(name) | Same name everywhere | Lookups on macOS need both forms |
| Excel opens UTF-8 CSV as garbage | سلام in Excel | Write a UTF-8 BOM first | EF BB BF prefix | Excel auto-detects | Other parsers must strip the BOM |
| Integer or float surprises | 0.30000000000000004, 2038 wrap | Integers for money; int64; tolerance for floats | int64 cents, bigint, numeric | Exact | Conversions at the edges |
Repair a double-encoded column Important
Take a backup first. In MySQL, text that was UTF-8 but stored as if it were Latin-1 can be repaired in two steps without losing bytes:
-- MySQL: column is declared latin1 but holds UTF-8 bytes.
ALTER TABLE users MODIFY full_name VARBINARY(400); -- reinterpret as raw bytes
ALTER TABLE users MODIFY full_name VARCHAR(100) CHARACTER SET utf8mb4;
-- Or in one statement: CONVERT(CAST(CONVERT(full_name USING latin1) AS BINARY) USING utf8mb4)Go (convert/main.go above) does the same in memory: encode back to the wrong charset's bytes and decode as UTF-8. PHP:
// Text that was UTF-8, decoded as Windows-1252 and saved as UTF-8 again.
$fixed = mb_convert_encoding($mojibake, 'Windows-1252', 'UTF-8'); // back to the original bytes
// $fixed now holds the original UTF-8 bytes; verify before saving:
if (! mb_check_encoding($fixed, 'UTF-8')) {
throw new RuntimeException('Not repairable: bytes were lost');
}Mixed yeh/kaf search in PostgreSQL Must-know
The fix is a generated search-key column that maps Arabic letters to Persian, removes tatweel and ZWNJ, converts digits and lower-cases. The column is derived, so it cannot drift from the display name.
-- PostgreSQL 12+ (generated columns). U&'\064A' is the SQL escape for U+064A.
CREATE TABLE users (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
full_name text NOT NULL,
full_name_key text GENERATED ALWAYS AS (
lower(
translate(
replace(replace(full_name, U&'\200C', ''), U&'\0640', ''),
U&'\064A\0649\0643' || '٠١٢٣٤٥٦٧٨٩۰۱۲۳۴۵۶۷۸۹',
U&'\06CC\06CC\06A9' || '01234567890123456789'
)
)
) STORED
);
CREATE INDEX users_name_key_idx ON users (full_name_key text_pattern_ops); -- prefix search
-- substring search: CREATE EXTENSION pg_trgm; CREATE INDEX ... USING gin (full_name_key gin_trgm_ops);
SELECT id, full_name FROM users
WHERE full_name_key LIKE lower(translate($1, U&'\064A\0649\0643', U&'\06CC\06CC\06A9')) || '%';Go (matching in the application, same map as persian.SearchKey):
key := persian.SearchKey(term)
rows, err := db.QueryContext(ctx,
`SELECT id, full_name FROM users WHERE full_name_key LIKE $1 || '%'`, key)Laravel: the User model below fills full_name_key on every save and exposes searchName(), so Arabic and Persian spellings, ZWNJ and digits all match. The migration adds the column with a normal index (MySQL) or you create the PostgreSQL generated column in raw SQL.
<?php
declare(strict_types=1);
namespace App\Models;
use App\Support\Text\PersianNormalizer;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
/**
* @property string $username
* @property string $full_name
* @property string $full_name_key
*/
final class User extends Model
{
protected $fillable = ['username', 'full_name'];
protected static function booted(): void
{
// Keep the lossy search key in sync; the display name stays untouched.
static::saving(function (self $user): void {
$user->full_name = PersianNormalizer::canonical($user->full_name);
$user->full_name_key = PersianNormalizer::searchKey($user->full_name);
});
}
/** Search by the normalized key: Arabic/Persian yeh and kaf, ZWNJ and digits all match. */
public function scopeSearchName(Builder $query, string $term): Builder
{
$key = PersianNormalizer::searchKey($term);
return $query->where('full_name_key', 'like', '%' . addcslashes($key, '%_\\') . '%');
}
}<?php
declare(strict_types=1);
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
public function up(): void
{
Schema::create('users', function (Blueprint $table): void {
// MySQL: always utf8mb4 (utf8 is the 3-byte utf8mb3 alias and loses emoji).
$table->charset('utf8mb4');
$table->collation('utf8mb4_unicode_ci'); // works on MySQL 5.7+, 8.x and MariaDB; MySQL 8 default is utf8mb4_0900_ai_ci
$table->id();
$table->string('username', 30)->unique();
$table->string('full_name', 100);
// Lossy search key (PersianNormalizer::searchKey), filled by the model; used only for matching.
$table->string('full_name_key', 120)->index();
$table->timestamps();
});
}
public function down(): void
{
Schema::dropIfExists('users');
}
};Why not a collation? ICU and MySQL collations can ignore case and accents, but this page does not claim that any of them treats U+064A and U+06CC, or U+0643 and U+06A9, as equal; they are different letters in Unicode, and canonical normalization leaves them apart (NFKC of both Arabic and Persian yeh returns them unchanged, as the Python check in the lab shows). A derived key column is explicit, portable across PostgreSQL and MySQL, and testable.
Truncate safely Important
Go uses truncateBytes from runes/main.go (utf8.RuneStart loop). PHP:
$preview = mb_strcut($text, 0, 20, 'UTF-8'); // at most 20 BYTES, never splits a character
$chars = mb_substr($text, 0, 20, 'UTF-8'); // exactly 20 code points
$visible = grapheme_substr($text, 0, 20); // 20 graphemes (ext-intl)SQL: LEFT(col, 20) counts characters in PostgreSQL and MySQL; SUBSTRING(col FROM 1 FOR 20) likewise; byteacat-style byte slicing on bytea is the unsafe one.
Usernames, look-alikes and invisible characters Must-know
Rules that work: (1) canonicalize with NFKC and lower-case; (2) accept an allow-list (ASCII ^[a-z0-9_]{3,30}$, or one script plus digits); (3) reject any \p{Cc}, \p{Cf} (except ZWNJ in display names), \p{Zl}, \p{Zp} and mixed scripts; (4) put the unique index on the normalized key, not the display value. The StoreUserRequest form request does (2) and (3) with Laravel validation; the middleware does (1) once at the boundary.
<?php
declare(strict_types=1);
namespace App\Http\Middleware;
use App\Support\Text\PersianNormalizer;
use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;
/**
* Canonicalizes string input once, at the HTTP boundary, before validation.
* Only the lossless storage form is applied everywhere; fields that are numbers
* by nature additionally get ASCII digits. Lossy search keys are built in the model.
* Register it in bootstrap/app.php: $middleware->append(NormalizeInput::class);
* Laravel already ships TrimStrings and ConvertEmptyStringsToNull; this runs after them.
*/
final class NormalizeInput
{
/** Fields that are numbers by nature: Persian and Arabic-Indic digits become ASCII. */
private const DIGIT_FIELDS = ['postal_code', 'phone', 'national_id', 'card_number'];
/** Fields that must stay byte-exact (passwords, tokens, signatures). */
private const SKIP = ['password', 'password_confirmation', 'current_password', 'token', 'signature'];
public function handle(Request $request, Closure $next): Response
{
$request->merge($this->clean($request->all()));
return $next($request);
}
/** @param array<string,mixed> $data */
private function clean(array $data): array
{
foreach ($data as $key => $value) {
if (in_array($key, self::SKIP, true)) {
continue;
}
if (is_array($value)) {
$data[$key] = $this->clean($value);
} elseif (is_string($value) && mb_check_encoding($value, 'UTF-8')) {
$value = PersianNormalizer::canonical($value);
$data[$key] = in_array($key, self::DIGIT_FIELDS, true) ? PersianNormalizer::digits($value) : $value;
}
// Invalid UTF-8 is left alone so the "string" and custom rules can reject it.
}
return $data;
}
}<?php
declare(strict_types=1);
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rule;
final class StoreUserRequest extends FormRequest
{
/** @return array<string,mixed> */
public function rules(): array
{
return [
// Persian letters, ZWNJ, spaces. No Latin, no digits.
'full_name' => ['required', 'string', 'max:100', 'regex:/^[\x{0600}-\x{06FF}\x{200C}\s]+$/u'],
// ASCII-only handle: stops look-alike (homoglyph) accounts.
'username' => ['required', 'string', 'min:3', 'max:30', 'regex:/^[a-z0-9_]+$/', Rule::unique('users', 'username')],
// max counts characters (code points), not bytes, in Laravel's Validator.
'bio' => ['nullable', 'string', 'max:500'],
// Postal code accepts Persian digits only after NormalizeInput converted them to ASCII.
'postal_code' => ['required', 'digits:10'],
];
}
/** Reject invisible or control characters that survive normalization. */
public function after(): array
{
return [
function ($validator): void {
foreach (['full_name', 'username'] as $field) {
$value = (string) $this->input($field);
// \p{Cc} control, \p{Cf} format (except ZWNJ allowed in names), \p{Zl}\p{Zp} separators
if (preg_match('/[\p{Cc}\p{Zl}\p{Zp}]/u', $value) === 1
|| ($field === 'username' && preg_match('/\p{Cf}/u', $value) === 1)) {
$validator->errors()->add($field, 'Contains invisible characters.');
}
}
},
];
}
}Go's equivalent middleware, with real output:
// An HTTP middleware that rejects invalid UTF-8 and canonicalizes form values.
package main
import (
"fmt"
"net/http"
"net/http/httptest"
"net/url"
"strings"
"unicode/utf8"
"academy/bits-bytes-text-encoding/persian"
)
// Canonicalize validates UTF-8 once at the edge and rewrites r.Form and r.PostForm.
func Canonicalize(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if err := r.ParseForm(); err != nil {
http.Error(w, "bad form", http.StatusBadRequest)
return
}
for _, vals := range []url.Values{r.Form, r.PostForm} {
for k, vs := range vals {
for i, v := range vs {
if !utf8.ValidString(v) {
http.Error(w, "invalid UTF-8 in field "+k, http.StatusBadRequest)
return
}
v = persian.Canonical(v)
if k == "postal_code" || k == "phone" {
v = persian.Digits(v)
}
vs[i] = v
}
}
}
next.ServeHTTP(w, r)
})
}
func main() {
h := Canonicalize(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "name=%U postal=%s", []rune(r.PostFormValue("name")), r.PostFormValue("postal_code"))
}))
// Arabic yeh (U+064A) and Persian digits in the request body.
body := url.Values{"name": {"علي"}, "postal_code": {"۱۲۳۴۵"}}.Encode()
req := httptest.NewRequest(http.MethodPost, "/", strings.NewReader(body))
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
fmt.Println(rec.Code, rec.Body.String())
// Invalid UTF-8 (a lone Latin-1 e-acute byte, %E9) is rejected with 400.
bad := httptest.NewRequest(http.MethodPost, "/", strings.NewReader("name=caf%E9"))
bad.Header.Set("Content-Type", "application/x-www-form-urlencoded")
rec = httptest.NewRecorder()
h.ServeHTTP(rec, bad)
fmt.Print(rec.Code, " ", rec.Body.String())
}$ go run ./middleware
200 name=[U+0639 U+0644 U+06CC] postal=12345
400 invalid UTF-8 in field nameTransliteration for slugs is a different job: Str::ascii() (Laravel) and iconv('UTF-8', 'ASCII//TRANSLIT', ...) produce ASCII but are lossy and platform-dependent; use them for URLs and file names, never for identity checks.
<?php
declare(strict_types=1);
use Illuminate\Support\Str;
// Str::ascii transliterates to ASCII (language-aware). It is for slugs and file names, not for Persian search.
Str::ascii("caf\u{00E9}"); // "cafe"
Str::ascii("\u{0633}\u{0644}\u{0627}\u{0645}"); // transliteration of Persian letters, lossy and not reversible
Str::slug('Hello World', '-'); // "hello-world"
Str::slug("\u{0633}\u{0644}\u{0627}\u{0645} \u{062F}\u{0646}\u{06CC}\u{0627}", '-', 'fa'); // keep a stable slug per language
// Length: Str::length counts characters (mb_strlen); Str::of()->length() is the same.
Str::length("\u{0633}\u{0644}\u{0627}\u{0645}"); // 4
// Reverse and limit are multibyte-safe but NOT grapheme-safe.
Str::limit("\u{1F468}\u{200D}\u{1F469}\u{200D}\u{1F467} family", 2, '...'); // may cut the ZWJ sequenceFile names and Excel CSV Good to know
Compare and store file names in NFC (norm.NFC.String(name) in Go, Normalizer::normalize($name, Normalizer::FORM_C) in PHP) and keep the original bytes if you must hand them back to the filesystem. For Excel, write the BOM yourself:
w.Write([]byte{0xEF, 0xBB, 0xBF}) // UTF-8 BOM so Excel detects UTF-8
csv.NewWriter(w).WriteAll(rows)return response("\xEF\xBB\xBF" . $csv, 200, ['Content-Type' => 'text/csv; charset=UTF-8']);Choosing
| Situation | Choose | Extra technique | Reason |
|---|---|---|---|
| New project, any storage | UTF-8 everywhere (utf8mb4, PostgreSQL UTF8) | Validate at the edge | One encoding, ASCII-compatible, the web's default |
| MySQL tables from the 5.x era | Convert to utf8mb4 | ALTER TABLE ... CONVERT TO CHARACTER SET utf8mb4, check index key lengths | utf8/utf8mb3 drops emoji and U+10000+ |
| Windows APIs, Java, JavaScript interop | UTF-16 only at the boundary | Always label LE/BE or use a BOM | Their native string unit |
| Binary wire format (custom, RPC) | Big-endian (network order) or a schema format | Document the order; test with xxd | Interop with other languages and CPUs; or use Protobuf and friends |
| Storing text for display | NFC, keep ZWNJ | Canonical form only | Lossless |
| Matching or de-duplicating text | Separate lossy key (NFKC, folding, Persian map) | Same function on index and query | Predictable matching without damaging the display value |
| Money | Integer minor units or numeric | Never float | Exactness |
| IDs from JavaScript clients | Strings for 64-bit integers | bigint in storage | Numbers beyond 2^53 lose precision |
| Length limit for users | Graphemes (or code points) | Bytes at the storage layer | What a person counts vs what the row holds |
| Legacy import (Windows-1256) | Convert once at ingest | Keep original bytes and the declared charset | Idempotent, debuggable |
| Excel-facing CSV | UTF-8 with BOM | Or UTF-16LE with BOM tab-separated | Excel's detection rules |
| Passwords | NFKC before hashing (NIST SP 800-63B) | Hash the bytes | Same password from different keyboards |
In architecture: from a single process to a distributed system
The rule of the whole path: a byte sequence only means something together with its declared encoding, so every component boundary needs the encoding, the byte order and the normalization form to be written down, tested and identical on both sides.
Monolith (one process, one database)
Everyday example: a Laravel blog on MySQL. The migration sets utf8mb4, the config/database.php connection sets 'charset' => 'utf8mb4', Blade emits <meta charset="utf-8">, and the NormalizeInput middleware makes yeh/kaf and digits consistent once. Search uses the full_name_key-style column. This setup removes 90% of encoding bugs; the remaining ones are substr on UTF-8 and the BOM at the start of a PHP file.
Production example: a Go monolith with PostgreSQL that imports CSV from partners. The importer validates with utf8.Valid, falls back to charmap.Windows1256 when a file fails validation and carries a Persian-looking byte distribution, stores normalized = persian.Canonical(name) plus search_key = persian.SearchKey(name), and rejects Cf characters in identifiers.
Modular monolith or several databases
Modules must agree on one canonical text form. A shared package (the Go persian package or the PHP PersianNormalizer) is the single implementation; each module calls it at its public boundary. Database-per-module is fine as long as every database is UTF8; mixing utf8mb4_unicode_ci and utf8mb4_0900_ai_ci columns in a join raises MySQL error 1267 "Illegal mix of collations". Cross-module identifiers (user handles, SKUs) are stored once in their canonical form and referenced by ID, never re-normalized per module.
Microservices
Each service boundary is an encoding boundary: HTTP/JSON (UTF-8, RFC 8259), gRPC/Protobuf (the string type is UTF-8; bytes is not text), message brokers (bytes plus a header saying content type and charset), and binary protocols (byte order). A realistic failure: a Go service sends Name in NFC, a PHP service compares against an NFD copy it stored earlier, and an idempotency key or cache key built from the name differs. Pin the form in the contract ("strings are UTF-8 NFC") and test with contract tests that include é (NFC and NFD), a ZWNJ and an emoji. For the broker side see Designing for failure and reliable messaging and for formats see Serialization Formats.
Distributed data (replicas, caches, search)
Replicas inherit the primary's encoding and collation, so a collation or ICU version difference between primary and replica (or after an OS upgrade) can make the same query order rows differently and corrupt btree indexes; check pg_collation_actual_version and plan REINDEX. Caches (Redis, Memcached) are binary-safe, so the application owns the encoding: build cache keys from the canonical form, never from raw input, or you will cache the same user twice (NFC and NFD, Arabic and Persian yeh). A search engine (Elasticsearch, OpenSearch, Meilisearch, Typesense) applies its own analyzers: configure Persian normalization (the persian_normalization and arabic_normalization token filters in Elasticsearch) or send the pre-normalized search_key; the index and the query must use the same analyzer. Cross-region replication and logs are byte streams: strip control and bidi characters before writing logs to prevent log forging and display reordering.
Scaling path
| Scale | What changes for text and bytes | Action |
|---|---|---|
| 1x (one app, one database) | Encoding settings and a normalization function | utf8mb4/UTF8, middleware, search key column |
| 10x (replicas, cache, queue) | Many readers and writers must agree | Shared normalizer package, canonical cache keys, contract tests with Persian and emoji samples |
| 100x (sharding, multi-region, search cluster) | Collation/ICU drift, shard keys and consistent hashing over text, reindex cost | Hash the canonical bytes (see Consistent Hashing), pin collation versions, version the normalizer (changing it means a reindex), prefer binary formats with explicit byte order |
Troubleshooting
| Symptom | Likely cause | Check | Fix |
|---|---|---|---|
é instead of é | UTF-8 read as Latin-1/cp1252 | xxd shows c3 a9; reader label says latin1 | Decode as UTF-8; fix the charset |
? where Persian letters should be | Stored in a narrow charset (lossy) | Column charset; SHOW CREATE TABLE; hex of the stored value shows 3f | Convert column to utf8mb4; re-import |
Incorrect string value: '\xF0\x9F...' | utf8mb3 column | SHOW CREATE TABLE users | ALTER TABLE ... CONVERT TO CHARACTER SET utf8mb4 |
invalid byte sequence for encoding "UTF8" | Latin-1 or truncated bytes sent to PostgreSQL | Hex of the offending value | Convert or validate at the edge |
json_encode returns false | Invalid UTF-8 (often from substr) | mb_check_encoding | Use mb_substr/mb_strcut |
Search for کتاب finds nothing | Arabic kaf/yeh in data or query | Hex of both strings: 06A9 vs 0643 | Search key column |
| Two users "the same" but both allowed | NFC vs NFD or look-alikes | Compare NFC/NFKC forms | Normalize before the unique check |
| Username "taken" but not found | Invisible RLM/ZWNJ/BOM | xxd shows e2 80 8f/e2 80 8c/ef bb bf | Strip bidi and Cf in identifiers |
| Persian text order reversed or scrambled | Visual-order data or bidi controls | Are there U+202x/U+2066..2069 controls? | Store logical order; use dir="rtl" or <bdi> in HTML |
| Digits ۱۲۳ rejected by validation | Persian digits vs ASCII-only rule | Code points U+06F1.. | Convert with Digits for numeric fields |
| Excel shows garbage | CSV without BOM | First bytes of the file | Add EF BB BF |
File café.txt not found on Linux | NFD name from macOS | `ls | xxdshows65 cc 81` |
| Counter or ID suddenly negative or 0 | Integer overflow or wrong width | Column type; bit width | Widen type; check before arithmetic |
| Packets parse with wrong values | Byte order mismatch | Dump bytes; compare with the spec | binary.BigEndian / pack('N') |
| Same query sorts differently after upgrade | ICU/glibc collation version change | pg_collation_actual_version; REINDEX | Pin collation, reindex |
| Emoji split or truncated | Cutting at bytes or code points | utf8.ValidString; graphemes | Truncate at grapheme or rune boundary |
Lab
Everything below runs on one machine. Go and the standard shell tools are enough for experiments 1 to 4 (real output was captured on macOS (Darwin 27), Apple silicon). Experiment 5 needs PostgreSQL (docker run --rm -e POSTGRES_PASSWORD=pw -p 5432:5432 postgres:17); its output here is the expected result from the documented semantics of translate() and generated columns, not a captured run, because no Docker daemon was available while writing.
cd docs/snippets/foundations/bits-bytes-text-encoding/go
go vet ./... && go test ./... # all snippets compile; the persian tests pass1. The same Persian word in UTF-8 and UTF-16, in hex.
printf 'سلام' | xxd
printf 'سلام' | iconv -f UTF-8 -t UTF-16LE | xxd
printf 'سلام' | iconv -f UTF-8 -t UTF-16BE | xxd
printf 'سلام' | iconv -f UTF-8 -t UTF-32BE | xxd00000000: d8b3 d984 d8a7 d985 ........ # UTF-8: 8 bytes
00000000: 3306 4406 2706 4506 3.D.'.E. # UTF-16LE: 33 06 = U+0633
00000000: 0633 0644 0627 0645 .3.D.'.E # UTF-16BE
00000000: 0000 0633 0000 0644 0000 0627 0000 0645 ...3...D...'...E # UTF-32BE: 16 bytesQuestion: which byte pairs swap between LE and BE? (Each 16-bit unit.) What would reading the LE bytes as BE give for the first letter? 3306 becomes U+3306, a CJK square symbol, which Python confirms: 'سلام'.encode('utf-16-le').decode('utf-16-be') yields ㌆䐆✆䔆.
2. Break a string by slicing bytes.
go run ./runesExpected: s[:3] : d8 b3 d9 valid UTF-8? false, then printed : "س\xd9", then the safe truncation "س" (see the output printed above in String length pitfalls). Try echo -n 'سلام' | head -c 3 | xxd and then | iconv -f UTF-8 -t UTF-16LE, which fails with iconv: unexpected end of file; the last character is incomplete.
3. Normalize NFD vs NFC and compare.
go run ./norm
printf 'caf\xc3\xa9' | xxd ; printf 'cafe\xcc\x81' | xxd00000000: 6361 66c3 a9 caf.. # NFC: 5 bytes
00000000: 6361 6665 cc81 cafe.. # NFD: 6 bytes== on the strings is false and norm.NFC.String(a) == norm.NFC.String(b) is true.
4. Endianness and the float.
go run ./endian
python3 -c "import struct; print(struct.pack('>I',0x0A0B0C0D).hex(), struct.pack('<I',0x0A0B0C0D).hex(), (0.1).hex(), 0.1+0.2)"0a0b0c0d 0d0c0b0a 0x1.999999999999ap-4 0.300000000000000045. Mixed yeh/kaf search bug in PostgreSQL, and the fix.
CREATE TABLE books_bad (title text);
-- Persian title typed on a Persian keyboard: U+06A9 U+062A U+0627 U+0628
INSERT INTO books_bad VALUES (U&'\06A9\062A\0627\0628');
-- Search typed on an Arabic keyboard: U+0643 U+062A U+0627 U+0628
SELECT count(*) FROM books_bad WHERE title = U&'\0643\062A\0627\0628';
-- count
-- -------
-- 0 <- the bug: same visible word, different code points
SELECT title = U&'\0643\062A\0627\0628' AS equal_bytes,
normalize(title, NFKC) = normalize(U&'\0643\062A\0627\0628', NFKC) AS equal_nfkc
FROM books_bad;
-- equal_bytes | equal_nfkc
-- -------------+-----------
-- f | f <- normalization does not unify kaf and keheh
-- The fix: map Arabic letters to Persian in a key, compare keys.
SELECT translate(U&'\0643\062A\0627\0628', U&'\064A\0649\0643', U&'\06CC\06CC\06A9')
= translate(title, U&'\064A\0649\0643', U&'\06CC\06CC\06A9') AS equal_keys
FROM books_bad;
-- equal_keys
-- ------------
-- tThen create the generated-column table from Mixed yeh/kaf search and run the LIKE query with an Arabic-keyboard term. Python check that NFKC leaves both yeh letters unchanged (real output): NFKC leaves Arabic yeh alone: True True.
6. Look at ZWNJ in a dump (real output).
echo -n "سلام میخواهم" | hexdump -CFind e2 80 8c at offset 0x0d: that is U+200C. Delete those three bytes and compare the two strings: they print almost identically, and a byte comparison says they differ.
Common misconceptions
| Belief | Reality |
|---|---|
| "Unicode is a 16-bit encoding" | Unicode is a character set up to U+10FFFF; UTF-8, UTF-16 and UTF-32 are encodings |
"len(s) is the number of characters" | Go len and PHP strlen count bytes; mb_strlen counts code points; users count graphemes |
| "UTF-8 needs a BOM" | UTF-8 has no byte order; a BOM is unnecessary and breaks JSON and PHP headers; only Excel CSV wants it |
"utf8 in MySQL is UTF-8" | utf8 is utf8mb3, 3 bytes per character, no emoji; use utf8mb4 |
"VARCHAR(255) is 255 bytes everywhere" | Characters in PostgreSQL and MySQL; bytes by default in Oracle; byte-pairs for nvarchar in SQL Server |
| "Equal-looking strings are equal" | NFC vs NFD, Arabic vs Persian yeh and kaf, and invisible characters make them different |
| "NFKC fixes Arabic yeh and kaf" | Canonical and compatibility normalization do not map U+064A to U+06CC or U+0643 to U+06A9 |
| "Strip all invisible characters" | ZWNJ is meaningful in Persian words; remove it only from search keys |
"0.1 + 0.2 is a bug in my language" | It is IEEE 754 binary floating point in every language |
| "Integer overflow throws" | Go, C and Java wrap silently; PHP converts to float; only some databases raise errors |
| "Little-endian means text is reversed" | Byte order affects multi-byte numbers and UTF-16/32; UTF-8 text is unaffected |
| "I can detect the encoding reliably" | Detection is statistical; ask the producer and record the label |
"Case-insensitive means LOWER()" | Locale rules (Turkish I, German ß) and normalization matter; use case folding or a collation |
Cheat sheet
| Topic | What to remember |
|---|---|
| Layers | Grapheme cluster, code point, code unit, byte: count the layer the rule is about |
| UTF-8 patterns | 0xxxxxxx, 110xxxxx 10xxxxxx, 1110xxxx 10xxxxxx 10xxxxxx, 11110xxx plus three continuations |
| Persian in UTF-8 | Letters in U+0600-U+06FF take 2 bytes; ZWNJ e2 80 8c; Persian yeh db 8c, Arabic yeh d9 8a |
| Byte order | Network order is big-endian; binary.BigEndian, pack('N'), htonl; x86 and ARM are little-endian |
| Integers | Two's complement; overflow wraps in Go; PHP turns into float; use bigint and int64 |
| Floats | IEEE 754; never ==; money in integers or numeric |
| BOM | EF BB BF UTF-8, FF FE UTF-16LE, FE FF UTF-16BE; JSON must not have one |
| Normalization | NFC for storage; NFKC plus fold plus Persian map for search keys; NFKC is lossy |
| Yeh and kaf | Map U+064A, U+0649 to U+06CC and U+0643 to U+06A9; neither NFC nor NFKC does it |
| Length functions | Go len, PHP strlen: bytes. mb_strlen, utf8.RuneCountInString: code points. grapheme_strlen, uniseg: graphemes |
| MySQL | utf8mb4 always; utf8 is utf8mb3; error 1366 is the symptom |
| PostgreSQL | UTF8 encoding; client_encoding; normalize(); varchar(n) counts characters |
| Boundaries | Declare UTF-8 on HTTP, DB connection, files and terminals; JSON is UTF-8 |
| Hex dump | xxd, hexdump -C: dump the bytes first when text looks wrong |
| Truncation | Cut at rune or grapheme boundaries: utf8.RuneStart, mb_strcut, grapheme_substr |
| Conversion | iconv -f A -t B, x/text/encoding/charmap, mb_convert_encoding; keep original bytes |
Self-check: questions & answers
- Must-know asked in almost every interview
- Important frequent; expected at senior level
- Good to know extra depth that sets you apart
1 — How many bytes, code points and graphemes does the Persian word سلام have in UTF-8? Must-know
Answer
Answer: 8 bytes (d8 b3 d9 84 d8 a7 d9 85), 4 code points, 4 graphemes. Go len gives 8, utf8.RuneCountInString gives 4.
2 — Why is 0.1 + 0.2 == 0.3 false in Go, PHP and JavaScript? Must-know
Answer
Answer: 0.1 and 0.2 have no exact binary representation; their IEEE 754 sum is 0x3fd3333333333334, one unit in the last place above 0x3fd3333333333333 (0.3). Compare with a tolerance or use integers or decimals.
3 — Which bytes does binary.BigEndian.PutUint32 write for 0x0A0B0C0D and what does reading them as little-endian give? Important
Answer
Answer: 0a 0b 0c 0d; read as little-endian the value is 0x0D0C0B0A. Network byte order is big-endian.
4 — Why can substr($s, 0, 3) on UTF-8 text break json_encode? Must-know
Answer
Answer: It cuts bytes and can leave a partial multi-byte sequence (d8 b3 d9), which is invalid UTF-8, so json_encode returns false with "Malformed UTF-8". Use mb_strcut or mb_substr.
5 — What is the difference between NFC and NFKC, and which do you store? Important
Answer
Answer: NFC composes canonically equivalent sequences without losing meaning; NFKC also folds compatibility variants (fi to fi, presentation forms to base letters) and is lossy. Store NFC; use NFKC only for search keys and identifiers.
6 — Do NFC or NFKC make Arabic yeh (U+064A) equal to Persian yeh (U+06CC)? Good to know
Answer
Answer: No. They are different letters; Python shows NFKC leaves both unchanged. Map them yourself (Canonical / searchKey) or compare a derived key.
7 — Why keep ZWNJ in stored Persian text but remove it from a search key? Important
Answer
Answer: ZWNJ (U+200C) is part of correct spelling (میخواهم), so stored text keeps it. Users type words with or without it, so a search key removes it to match both.
8 — What does VARCHAR(10) limit in PostgreSQL, MySQL, Oracle (default) and SQL Server nvarchar(10)? Important
Answer
Answer: PostgreSQL and MySQL: 10 characters. Oracle VARCHAR2(10) with default BYTE semantics: 10 bytes, so 5 Persian letters. SQL Server nvarchar(10): 10 byte-pairs, so a supplementary character counts as two.
9 — How do you recognise UTF-16LE with BOM in a hex dump, and how is U+1F600 written in it? Good to know
Answer
Answer: The file starts with ff fe; U+1F600 is the surrogate pair D83D DE00, stored as 3d d8 00 de.
10 — Why is MySQL utf8 unsafe for emoji, and what is the symptom? Must-know
Answer
Answer: utf8 means utf8mb3, at most 3 bytes per character; emoji need 4. Strict mode raises error 1366 Incorrect string value: '\xF0\x9F...'; the fix is utf8mb4.
11 — Where does a middleware belong that canonicalizes input, and what must it skip? Important
Answer
Answer: At the HTTP boundary, before validation. It must skip passwords, tokens and signatures (byte-exact values) and leave invalid UTF-8 to be rejected.
Glossary
| Term | Definition |
|---|---|
| Bit | One binary digit, 0 or 1 |
| Nibble | 4 bits, one hex digit |
| Byte / octet | 8 bits; the smallest addressable unit |
| Word | The natural integer size of a CPU or format; varies |
| Two's complement | Signed integer representation; negate by inverting and adding 1 |
| Overflow / wrap-around | Result exceeds the type's range; Go discards high bits |
| IEEE 754 | The standard for binary floating-point numbers (float32, float64) |
| NaN | "Not a number"; never equal to itself |
| Endianness | Order of bytes of a multi-byte number in memory or on the wire |
| Big-endian | Most significant byte first; network byte order |
| Little-endian | Least significant byte first; x86, ARM (default) |
htons / htonl | Convert 16/32-bit values from host to network byte order |
| Character set | A set of characters with numbers |
| Encoding | A mapping from code points to bytes |
| Code page | A legacy charset and encoding in one (Windows-1252, Windows-1256) |
| ASCII | 7-bit character set, values 0-127 |
| ISO 8859-1 (Latin-1) | 8-bit Western European encoding |
| Windows-1252 | Latin-1 variant with printable characters at 0x80-0x9F |
| Mojibake | Garbled text from decoding with the wrong encoding |
| Unicode | The universal character set, U+0000 to U+10FFFF |
| Code point | A number assigned to a character, written U+XXXX |
| Plane | A block of 65,536 code points; 17 in total |
| BMP | Basic Multilingual Plane, U+0000-U+FFFF |
| Surrogate | U+D800-U+DFFF; UTF-16's trick for code points above U+FFFF |
| Scalar value | A code point that is not a surrogate |
| UTF-8 | Variable-width encoding, 1-4 bytes per code point |
| UTF-16 | 2 or 4 bytes per code point (a surrogate pair) |
| UTF-32 | 4 bytes per code point |
| BOM | U+FEFF at the start of a stream; EF BB BF in UTF-8 |
| Overlong encoding | Non-shortest UTF-8 form (for example C0 80); invalid |
| Self-synchronising | You can find a character boundary from any byte |
| Replacement character | U+FFFD, emitted for invalid input |
| Grapheme cluster | A user-perceived character, per UAX #29 |
| ZWJ | U+200D ZERO WIDTH JOINER; forces joining and glues emoji |
| ZWNJ | U+200C ZERO WIDTH NON-JOINER; prevents joining in Persian |
| RLM / LRM | U+200F / U+200E invisible direction marks |
| Bidi | Bidirectional text (right-to-left and left-to-right mixed) |
| Tatweel (kashida) | U+0640; elongation line, decoration only |
| Harakat | Arabic vowel marks U+064B-U+065F |
| Presentation forms | Pre-shaped Arabic glyph code points (U+FB50-U+FDFF, U+FE70-U+FEFF) |
| Yeh, kaf | Letters with Arabic (U+064A, U+0643) and Persian (U+06CC, U+06A9) code points |
| Normalization | Rewriting equivalent text to one form (NFC, NFD, NFKC, NFKD) |
| Canonical equivalence | Same abstract character, same appearance and behavior |
| Compatibility equivalence | Same text with formatting differences (ligatures, fullwidth) |
| Case folding | Mapping for caseless comparison (ß to ss) |
| Collation | Rules for comparing and sorting strings |
| Deterministic collation | Equal only if the bytes are equal (PostgreSQL term) |
utf8mb4 | MySQL's real UTF-8, up to 4 bytes per character |
utf8mb3 | MySQL's 3-byte subset, alias utf8 (deprecated) |
client_encoding | PostgreSQL session setting for the client's encoding |
mb_strlen / strlen | PHP code point count / byte count |
iconv | Command and library for converting encodings |
| Hex dump | Byte-by-byte view (xxd, hexdump -C) |
uniseg | Go module for grapheme, word and sentence segmentation |
x/text | Go extended text packages: encodings, normalization, collation, cases |
References
- RFC 3629, UTF-8, a transformation format of ISO 10646: https://www.rfc-editor.org/rfc/rfc3629
- RFC 2781, UTF-16, an encoding of ISO 10646: https://www.rfc-editor.org/rfc/rfc2781
- RFC 20, ASCII format for network interchange: https://www.rfc-editor.org/rfc/rfc20
- RFC 8259, The JSON Data Interchange Format: https://www.rfc-editor.org/rfc/rfc8259
- RFC 791, Internet Protocol, Appendix B (Data Transmission Order): https://www.rfc-editor.org/rfc/rfc791
- Unicode Standard Annex #15, Unicode Normalization Forms: https://unicode.org/reports/tr15/
- Unicode Standard Annex #29, Text Segmentation: https://unicode.org/reports/tr29/
- Unicode Standard Annex #9, Bidirectional Algorithm: https://unicode.org/reports/tr9/
- Unicode Character Database, UnicodeData.txt and SpecialCasing.txt: https://www.unicode.org/Public/UCD/latest/ucd/
- Unicode FAQ, UTF and BOM; Case mappings: https://unicode.org/faq/utf_bom.html, https://unicode.org/faq/casemap_charprop.html
- W3C Arabic Layout Requirements (ZWNJ): https://www.w3.org/TR/alreq/
- WHATWG Encoding Standard: https://encoding.spec.whatwg.org/
- Goldberg, What Every Computer Scientist Should Know About Floating-Point Arithmetic: https://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html
- Python tutorial, Floating-Point Arithmetic: Issues and Limitations: https://docs.python.org/3/tutorial/floatingpoint.html
- The Go Programming Language Specification, Numeric types: https://go.dev/ref/spec
- Go blog, Strings, bytes, runes and characters in Go: https://go.dev/blog/strings
- Go packages
encoding/binary,unicode/utf8,golang.org/x/text: https://pkg.go.dev/encoding/binary - PHP manual:
pack,mb_strlen,mb_convert_encoding,Normalizer, integer overflow: https://www.php.net/manual/en/function.pack.php - Laravel 13: Strings, Validation, Migrations: https://laravel.com/docs/13.x/strings
- PostgreSQL: Character Types, Collation Support, Character Set Support: https://www.postgresql.org/docs/current/datatype-character.html
- MySQL 8.4: utf8mb4, utf8mb3: https://dev.mysql.com/doc/refman/8.4/en/charset-unicode-utf8mb4.html
- SQL Server: nchar and nvarchar: https://learn.microsoft.com/en-us/sql/t-sql/data-types/nchar-and-nvarchar-transact-sql
- Oracle Database SQL Language Reference, Data Types: https://docs.oracle.com/en/database/oracle/oracle-database/19/sqlrf/Data-Types.html
- NIST SP 800-63B, Digital Identity Guidelines (Authentication): https://pages.nist.gov/800-63-3/sp800-63b.html
- UTF-8 Everywhere (opinion): https://utf8everywhere.org/