Skip to content

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 forGo to
What all 18 chapters of Foundations cover and in which orderThe Foundations path
A table you can memorise in one minuteEverything in one minute
Why bytes and text need an agreement at allWhy it exists
ASCII, ISO 8859, Windows-1252, Unicode, UTF-8: who and whenWhere it comes from
Bits, bytes, words, nibbles, kibibytesBits, bytes and words
int8 wrapping, two's complement, PHP_INT_MAX + 1Two's complement and overflow
0.1 + 0.2, NaN, infinity, float vs decimal for moneyFloating point
htons, binary.BigEndian, pack('N'), byte order in a hex dumpEndianness
"charset" vs "encoding", the layers of textCharacter set vs encoding
ASCII control characters and the 7-bit tableASCII
é, ?, ’ in your outputLatin-1, Windows-1252 and mojibake
Code points, planes, BMP, surrogates, U+1F600Unicode
Byte patterns, self-synchronising, overlong, BOMUTF-8
Surrogate pairs, Windows/Java/JavaScript, FF FEUTF-16 and UTF-32
Emoji, ZWJ, flags, "one character" that is five code pointsGrapheme clusters
ZWNJ, Arabic yeh/kaf, Persian digits, RTL marks, presentation formsPersian and Arabic specifics
NFC vs NFD vs NFKC vs NFKD, when to normalizeNormalization
ß, Turkish i, case folding, collations, utf8mb4 vs utf8mb3Collation and case folding
len vs strlen vs mb_strlen, VARCHAR(n) per engineString length pitfalls
HTTP charset, JSON, database client encoding, terminals, files, URLsEncoding at every boundary
iconv, file, x/text/encoding, mb_convert_encodingDetecting and converting
xxd, hexdump -C, reading a dumpReading hex dumps
What each tool, language and database really doesPer-tool and per-product behaviour
Decoder algorithm, surrogate math, error messages verbatimMechanics
Double encoding, truncation, yeh/kaf search, ZWNJ in IDs: Go, Laravel, SQL fixesSolving the classic problems
Which encoding, form and type for which jobChoosing
Monolith to distributed systemsIn architecture
A symptom you see and the likely causeTroubleshooting
Reproduce it all on your machineLab
Wrong beliefs, cheat sheet, questions, termsMisconceptions, 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.

FN 01 Data Representation and IntegrityFN 02 Networking for Developers01 Bits, bytes, text (you are here)02 Binary-to-text: Base64, hex, percent03 Serialization: JSON, Protobuf, CBOR04 Compression: gzip, Brotli, zstd05 Checksums and hashing06 Cryptography fundamentals07 Password hashing, signed tokens08 TLS in practice09 Network models: OSI, TCP/IP10 IP addressing, CIDR, routing11 NAT, DHCP, port forwarding12 DNS resolution for developers13 Ports, sockets, connections14 Firewalls, security groups15 Docker networking16 Kubernetes networking17 VPNs and tunnels | 18 Troubleshooting
#ChapterOne line
01Bits, Bytes & Text EncodingThis page: integers, floats, byte order, Unicode, UTF-8, normalization, Persian text.
02Binary-to-Text EncodingHow arbitrary bytes travel through text-only channels: Base64, Base32, hex, percent-encoding, data URIs.
03Serialization FormatsJSON, Protobuf, MessagePack, Avro, CBOR, XML: schema, size, speed, evolution.
04CompressionEntropy, Huffman, LZ77, gzip/zlib/deflate, Brotli, zstd, lz4, snappy and when each wins.
05Checksums & HashingParity, CRC32/CRC32C, xxHash, Murmur, SHA-2/3, BLAKE3, content addressing.
06Cryptography FundamentalsAES-GCM, ChaCha20, RSA/ECC/Ed25519, ECDH, KDFs, HMAC, signatures, randomness.
07Password Hashing & Signed Tokensbcrypt, Argon2, salts and peppers, HMAC-signed URLs, JWT/PASETO signing.
08TLS in PracticeThe handshake on the wire, certificates and chains, SNI/ALPN, mkcert, openssl s_client, certs in Docker and Kubernetes.
09Network ModelsOSI vs TCP/IP, encapsulation, what happens when you open a URL.
10IP AddressingIPv4/IPv6, private ranges, CIDR and subnet math, gateways, routing tables, ARP/NDP.
11NAT, DHCP & Port ForwardingNAT/PAT, port forwarding, DHCP lease flow, CGNAT, hairpin NAT.
12DNS Resolution for DevelopersResolvers, records, TTL and caching, /etc/hosts, resolv.conf, split DNS, DNS in containers.
13Ports, Sockets & ConnectionsEphemeral ports, TIME_WAIT, keepalive, backlog, conntrack; ss, lsof, tcpdump, nc, curl, dig.
14Firewallsiptables/nftables, security groups, network ACLs, egress control.
15Docker Networkingbridge, host, none, overlay, macvlan; port publishing, embedded DNS, Compose networks, the iptables rules Docker writes, MTU.
16Kubernetes NetworkingPod network and CNI, Services, kube-proxy, CoreDNS, Ingress and Gateway API, NetworkPolicy, egress NAT.
17VPNs & TunnelsSSH port forwarding, bastions, WireGuard, site-to-site vs client VPN, zero-trust access.
18Network Troubleshooting PlaybookRefused 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.

LayerWhat it isExample for the Persian word سلامWho counts it
Grapheme clusterWhat a reader calls one character4grapheme_strlen (PHP intl), uniseg (Go), Intl.Segmenter (JavaScript)
Code pointA number from U+0000 to U+10FFFF4 (U+0633 U+0644 U+0627 U+0645)mb_strlen, utf8.RuneCountInString, PostgreSQL length()
Code unitThe unit an encoding form usesUTF-8: 8, UTF-16: 4, UTF-32: 4strlen, len(s) in Go (UTF-8 bytes), JavaScript .length (UTF-16 units)
Byte8 bits on disk or on the wired8 b3 d9 84 d8 a7 d9 85octet_length(), LENGTH() in MySQL

The encodings.

EncodingBytes per code pointWhere you meet itThe trap
ASCII1 (7 bits used)Protocol keywords, HTTP methods, identifiersCannot hold é or ا
ISO 8859-1 (Latin-1)1Old Western European data, default of some old HTTP stacksEvery byte value is valid, so a wrong guess never errors, it just garbles
Windows-12521Old Windows files, "Latin-1" labels on the web0x80-0x9F are printable here, control codes in Latin-1
Windows-12561Old Arabic and Persian Windows filesHas پ چ ژ گ (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-81 to 4The web, JSON, Go strings, Linux, databases, GitCounting bytes as characters; BOM; overlong forms
UTF-162 or 4Windows APIs, Java, JavaScript, .NETByte order (BE/LE), surrogate pairs, BOM
UTF-324Internal use, some Python buildsFour times the size; still has byte order

The five habits.

SituationDo 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 textNormalize first (NFC for storage, a lossy key for matching)
Cutting, counting or truncating textDecide what the rule means (bytes, code points or graphemes) and use the function that counts that
Persian or Arabic inputUnify 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 wireName 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 trivialVariable width: indexing by character needs a scan
Only one language group per file or columnEvery script in one stream
A wrong guess still "works" and garbles silentlyA wrong guess usually errors loudly (invalid sequences)
Dozens of incompatible code pagesOne standard; legacy code pages become conversion work
Sorting and case rules hard-coded per code pageSorting 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 ​

  1. "A string is a list of characters, so length is the number of characters." In Go, len(s) is bytes; in PHP, strlen is bytes; in JavaScript, .length is UTF-16 units; in MySQL, LENGTH() is bytes. Even "characters" is ambiguous (code points vs graphemes).
  2. "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.
  3. "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 ​

YearEventSource
1969RFC 20 describes the 7-bit ASCII character set for network interchangeRFC 20, October 1969
Before Unicode8-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"
2000RFC 2781 defines how UTF-16 is serialized, with BOM and the UTF-16BE/UTF-16LE labelsRFC 2781
2003RFC 3629 restricts UTF-8 to U+10FFFF, forbids surrogates and overlong formsRFC 3629, November 2003
2017RFC 8259 (JSON) requires UTF-8 for JSON exchanged between systemsRFC 8259, December 2017
TodayThe WHATWG Encoding Standard defines how browsers decode; labels such as "latin1" and "iso-8859-1" are mapped to windows-1252WHATWG 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): -54

Real 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.

UnitSizeValuesSeen as
bit1 bit2boolean flag, one bit in a bitmask
nibble4 bits16one hex digit
byte (octet)8 bits256uint8, byte in Go, u_char
16-bit word2 bytes65,536uint16, TCP port numbers
32-bit word4 bytes4,294,967,296uint32, IPv4 address, Unix time in 32 bits
64-bit word8 bytes2^64uint64, 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--  -> 255

Real 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 engineRange / behaviour on overflowNotes
Go int8 / uint8-128..127 / 0..255, wraps silentlymath/bits and math.MaxInt64 constants; constant expressions that overflow are compile errors
Go int64-bit on 64-bit platforms (32 on 32-bit)Use int64 explicitly in wire formats
PHP int64-bit on 64-bit builds; overflow turns the result into floatPHP_INT_MAX, PHP_INT_SIZE; use intdiv, GMP or BCMath when exactness matters
PostgreSQL integer-2147483648..2147483647; error 22003 on overflowbigint is 8 bytes; numeric is exact and unbounded
MySQL INTsigned -2147483648..2147483647; UNSIGNED doubles the topStrict mode: error 1264 "Out of range value"; non-strict clamps silently
JavaScript Numberintegers exact only up to 2^53-1Use BigInt or a string for 64-bit IDs; JSON parsers lose digits
SQLiteintegers up to 8 bytes, stored in 1 to 8 bytesType 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  -> false

Real 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.

RepresentationExact for decimals?Typical useProduct notes
float64 / doubleNoScience, graphics, metricsGo float64; PHP float; PostgreSQL double precision; MySQL DOUBLE
float32 / realNo, fewer digitsGPUs, MLPostgreSQL real; MySQL FLOAT
Integer minor units (cents)YesMoney in codeGo int64; PHP int; PostgreSQL bigint
Decimal / numericYesMoney in DB, accountingPostgreSQL 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.

Value 0x0A0B0C0D stored at addresses a, a+1, a+2, a+3aa+1a+2a+30A0B0C0D0D0C0B0ABig-endianLittle-endianMSB firstLSB firstWho uses whatBig: network byte order (TCP/IP),Java class files, PNG, most ASN.1Little: x86-64, ARM (default), RISC-V,protobuf fixed32/fixed64UTF-16LE on WindowsRule: convert at the boundary, never trust host order on the wireGo binary.BigEndian | PHP pack N, n, J (BE), V, v, P (LE) | C htons, htonl
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 languageBig-endianLittle-endianHost orderNotes
Go encoding/binarybinary.BigEndian.PutUint32/Uint32, binary.Write(w, binary.BigEndian, v)binary.LittleEndiann/a (explicit always)binary.NativeEndian exists in recent Go for the host order; AppendUvarint for varints
PHP pack/unpackN (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 / POSIXhtons, htonl, ntohs, ntohlno standardnativeNeeded for struct sockaddr_in
Pythonstruct.pack('>I', v), int.to_bytes(4, 'big')'<I', 'little''='Prefix chooses order
Javadefault for ByteBuffer, class files.order(ByteOrder.LITTLE_ENDIAN)ByteOrder.nativeOrder()Data streams are big-endian
JavaScriptDataView default (big)DataView(..., true) flagUint32Array uses hostA classic trap with typed arrays
xxd, hexdump -Cshow bytes in memory ordersamen/ahexdump -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.

go
// 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: 0xffffffff

The 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
<?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 dependent

Character 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.

TermMeaningExampleWhere it is configured
Character set / repertoireWhich characters existUnicode, ASCIIStandards
Code pointA character's numberU+0627Unicode tables
Encoding formCode point to code unitsUTF-8, UTF-16Libraries
Encoding schemeForm plus byte orderUTF-16LEFile label, BOM
Code pageLegacy charset and encoding in oneWindows-1256Windows, old databases
charset in HTTP/MIMEAn encoding labelcharset=utf-8Content-Type header
MySQL "character set"An encoding of a column or connectionutf8mb4Column, table, server, connection
PostgreSQL "encoding"Database-level encodingUTF8CREATE 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.

RangeCharactersRemark
0x00-0x1F, 0x7FControl codesStrip or reject in identifiers and log lines
0x20-0x2FSpace, !"#$%&'()*+,-./Percent-encoding targets (see Binary-to-Text Encoding)
0x30-0x390-9Only these are digits for ctype_digit and Laravel's digits rule
0x41-0x5A, 0x61-0x7AA-Z, a-zCase 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 trip

Real 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 seeCauseFix
é, ü, èUTF-8 text decoded as Latin-1/cp1252Decode as UTF-8; repair by encode-to-cp1252 then decode-as-UTF-8
’, “, â€"UTF-8 punctuation decoded as cp1252Same
سلام for PersianUTF-8 Persian decoded as cp1252Same; every Persian letter becomes two Latin symbols
? or Ø replacing lettersLossy conversion to a narrow charsetData lost; re-import from source; switch to UTF-8
U+FFFD (replacement character)Decoder met invalid bytesFind the producer; do not store it
Letters correct but reversed orderBidi/visual-order dataSee 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).

go
// 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-8

Real 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.

ConceptRange or valueRemark
Code spaceU+0000..U+10FFFF1,114,112 code points
BMP (plane 0)U+0000..U+FFFFOne UTF-16 unit; 1 to 3 UTF-8 bytes
Supplementary planesU+10000..U+10FFFFTwo UTF-16 units (a surrogate pair); 4 UTF-8 bytes
SurrogatesU+D800..U+DFFFNot scalar values; invalid in UTF-8
Scalar valueany code point except surrogatesWhat Go's rune and well-formed UTF-8 can carry
NoncharactersU+FFFE, U+FFFF, U+FDD0..FDEF and othersReserved for internal use
Replacement characterU+FFFDWhat decoders emit for invalid input
Private useU+E000..U+F8FF, planes 15-16Application-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.

Code point rangeBytes (x = payload bit)U+0000..U+007F0xxxxxxxU+0080..U+07FF110xxxxx10xxxxxxU+0800..U+FFFF1110xxxx10xxxxxx10xxxxxxU+10000..U+10FFFF11110xxx10xxxxxx10xxxxxx10xxxxxxExample: U+0633 = 110 11000 | 10 110011 = D8 B3Example: U+1F600 = F0 9F 98 80 (4 bytes)Example: U+20AC = E2 82 AC (3 bytes)Self-synchronisingLead byte: 0, 110, 1110 or 11110.Continuation byte: always 10xxxxxx.Land anywhere: skip 10xxxxxx bytesand the next byte starts a character.ASCII bytes never appear insidea multi-byte sequence.Rejected by a strict decoderOverlong: C0 80 for U+0000Surrogates: ED A0 80..ED BF BFAbove U+10FFFF: F4 90.. and F5..FFBytes C0, C1, F5..FF never occur
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 -> reject

Real 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.

PropertyUTF-8Consequence
ASCII-compatibleBytes 0x00-0x7F mean the same as ASCIIOld parsers, strchr(',') and / splitting keep working
Self-synchronisingLead and continuation bytes are distinguishableSeek to any offset and resynchronise in at most 3 bytes
No byte-order issueCode unit is one byteA BOM is unnecessary; RFC 3629 notes it is always EF BB BF
Sorts like code pointsByte order equals code point ordermemcmp ordering equals code point ordering (not linguistic order)
Overlong and surrogate forms invalidStrict decoders reject themTreat decoder errors as invalid input
Size per scriptLatin 1 byte (+accents 2), Arabic/Persian/Hebrew/Greek/Cyrillic 2, most CJK 3, emoji 4Persian 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 00

Real 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.

PlatformInternal string formlength countsNote
GoUTF-8 bytesbytes (len)utf16.Encode([]rune(s)) for UTF-16
PHPbytes, any encodingbytes (strlen); mb_strlen counts code pointsmb_convert_encoding($s, 'UTF-16LE', 'UTF-8')
JavaScriptUTF-16 unitsunits (.length)[...s].length counts code points, Intl.Segmenter graphemes
Java / C#UTF-16 unitsunitscodePointCount in Java
Python 3code points (flexible representation)code pointslen('😀') is 1
PostgreSQLstored as UTF-8 in a UTF8 databaselength() counts charactersoctet_length() bytes
MySQLby column charsetCHAR_LENGTH characters, LENGTH bytesutf8mb4 max 4 bytes per character
SQL Servernvarchar is UTF-16 (UCS-2 semantics unless _SC collation)n counts byte-pairsMicrosoft: "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.

1. Grapheme cluster (what the user counts)UAX #29 rules; one family emoji, or one letter plus its marks2. Code points (Unicode scalar values)U+1F468 U+200D U+1F469 U+200D U+1F467 (ZWJ = U+200D)3. Code units (depends on the encoding form)UTF-8: 18 bytes | UTF-16: 8 units | UTF-32: 5 units4. Bytes (order matters for UTF-16/32)f0 9f 91 a8 e2 80 8d f0 9f 91 a9 ...Who counts whatGo len(s): bytesGo RuneCountInString: code pointsPHP strlen: bytesPHP mb_strlen: code pointsPHP grapheme_strlen: graphemesJS string.length: UTF-16 unitsPostgres length(): code pointsPostgres octet_length(): bytesMySQL CHAR_LENGTH: code pointsMySQL LENGTH: bytesPick the layer the rule is about.
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+FFFD

Real 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
LibraryCounts graphemes withNotes
Gogithub.com/rivo/uniseg (GraphemeClusterCount, NewGraphemes)Standard library has no grapheme API; x/text does not segment graphemes
PHPgrapheme_strlen, grapheme_substr, grapheme_extract (ext-intl)mb_* counts code points only
JavaScriptIntl.Segmenter(undefined, {granularity: 'grapheme'}).length is UTF-16 units
PostgreSQLno built-in grapheme lengthUse an extension or count in the app
MySQLno built-in grapheme lengthCHAR_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 pointNameRole
U+064AARABIC LETTER YEHArabic yeh; two dots below in the initial and medial forms; common in Arabic keyboards
U+06CCARABIC LETTER FARSI YEHPersian yeh, the correct letter in Persian text
U+0649ARABIC LETTER ALEF MAKSURADotless yeh-like letter in Arabic; sometimes typed for yeh
U+0643ARABIC LETTER KAFArabic kaf
U+06A9ARABIC LETTER KEHEHPersian kaf, the correct letter in Persian text
U+0629, U+0647, U+06C0TEH MARBUTA, HEH, HEH WITH YEH ABOVESometimes interchanged in noisy data
U+200CZERO WIDTH NON-JOINER (ZWNJ), category CfPrevents joining without a visible space: می‌خواهم
U+200DZERO WIDTH JOINER (ZWJ)Forces joining; also glues emoji
U+200E / U+200FLEFT-TO-RIGHT MARK / RIGHT-TO-LEFT MARKInvisible bidi direction hints
U+202B..U+202E, U+2066..U+2069Embedding, override and isolate controlsCan reorder text visually; strip from identifiers
U+061CARABIC LETTER MARKDirection mark used in Arabic text
U+0640ARABIC TATWEEL (kashida)Elongation line, decoration only
U+064B..U+065F, U+0670Harakat (fatha, kasra, shadda...), superscript alefVowel marks; usually dropped for search
U+06F0..U+06F9EXTENDED ARABIC-INDIC DIGITS ۰-۹Persian digits
U+0660..U+0669ARABIC-INDIC DIGITS ٠-٩Arabic digits; ٤ ٥ ٦ differ in shape from ۴ ۵ ۶
U+066B, U+066CARABIC DECIMAL SEPARATOR, THOUSANDS SEPARATORPunctuation inside Arabic-digit numbers
U+FB50..U+FDFF, U+FE70..U+FEFFArabic Presentation Forms-A and -BPre-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)  -> equal

Real 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.

ConcernStore asSearch asShow as
Yeh and kafPersian U+06CC, U+06A9samesame
ZWNJkeepremovekeep
Digits in textkeep what the user typed or localize on outputASCIIper locale (Persian or Latin digits)
Digits in numeric fields (phone, postal code, national ID)ASCIIASCIIPersian or Latin per UI
Harakatkeepremovekeep
Tatweelremoveremoveremove
Bidi marks (U+200E/F, U+202A..U+202E, U+2066..U+2069)remove in identifiers; keep in display text only if neededremoven/a
Presentation formsnormalize to base lettersNFKCbase 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.

go
// 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
<?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+0628

Real 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.

FormDoesLossy?Use it for
NFCCompose where possibleNo (canonical)Storage, interchange, comparison of canonical equivalents
NFDFully decomposeNo (canonical)Stripping accents (decompose, then drop Mn marks)
NFKCCompose and fold compatibility variantsYesSearch keys, identifiers, usernames (with care)
NFKDDecompose and fold compatibility variantsYesAggressive ASCII-folding pipelines
When to normalizeFormReason
At the input boundary, user-visible textNFCSame bytes for the same text; no loss
Usernames, handles, emails local-partNFKC plus case folding plus your own rulesBlock look-alikes and width tricks; follow your identity policy
File names across OSesNFC at your boundary (compare in NFC)macOS and Linux disagree on forms
Search index and queryNFKC plus case folding plus Persian mapSame transformation on both sides
Cryptographic input (hashes, signatures, passwords)Decide once and document; passwords are typically NFKC per NIST SP 800-63BThe 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.

go
// 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.

EngineDefault comparisonCase-insensitive optionsNotes
PostgreSQLDeterministic 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.4utf8mb4_0900_ai_ci (accent- and case-insensitive)_as_cs, _bin, utf8mb4_unicode_ci_ci collations make UNIQUE match A and a; _bin compares bytes
MariaDBDepends on the version_ci/_cs variantsCheck SHOW COLLATION and the server default
SQL Serverdatabase collation (for example SQL_Latin1_General_CP1_CI_AS)_CS, _CI, _AS, _AI, _UTF8Case and accent sensitivity are part of the collation name
OracleNLS_SORT, NLS_COMPBINARY_CI, GENERIC_M_CILinguistic sort is optional
SQLiteBINARYNOCASE (ASCII only)Full Unicode needs the ICU extension
Gobyte order for < and ==strings.EqualFold; golang.org/x/text/collate for locale orderx/text/cases for locale-aware casing
PHPbyte order for < and ==mb_strtolower, Collator (ext-intl), mb_convert_casestrcasecmp 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:

Productn in VARCHAR(n) countsStatement from the vendor docsGotcha
PostgreSQLcharacters"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)charactersCHAR(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
Oraclebytes 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 Servervarchar(n) bytes, nvarchar(n) byte-pairs"n never defines numbers of characters" for nvarchar(n); characters above U+FFFF use two byte-pairsA single emoji can need 2 of the 4,000 pairs
SQLitenot enforcedDeclared lengths are ignored (type affinity)The app must enforce limits
MongoDBno declared lengthBSON strings are UTF-8 with a length prefixThe document limit is in bytes (16 MiB)
OperationGoPHPPostgreSQLMySQLJavaScript
Byteslen(s)strlen($s)octet_length(s)LENGTH(s)new TextEncoder().encode(s).length
Code pointsutf8.RuneCountInString(s)mb_strlen($s, 'UTF-8')length(s), char_length(s)CHAR_LENGTH(s)[...s].length
UTF-16 unitslen(utf16.Encode([]rune(s)))strlen(mb_convert_encoding($s, 'UTF-16LE', 'UTF-8')) / 2n/an/as.length
Graphemesuniseg.GraphemeClusterCount(s)grapheme_strlen($s)n/an/aIntl.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.

go
// 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.

BoundaryHow the encoding is declaredDefault if you say nothingSet it to
HTTP responseContent-Type: text/html; charset=utf-8Browsers guess (WHATWG: windows-1252 for many legacy labels)charset=utf-8 and <meta charset="utf-8">
HTTP form postaccept-charset, Content-Type charsetPage encodingUTF-8 pages and forms
JSONnone (RFC 8259: UTF-8)UTF-8UTF-8, no BOM
URLs and query stringspercent-encoded UTF-8 bytes (RFC 3986 leaves the choice to the scheme; WHATWG URL uses UTF-8)n/aPercent-encode UTF-8; see Binary-to-Text Encoding
PostgreSQLdatabase ENCODING; session client_encodingDatabase encoding; client default from the server or driverUTF8 database; SET client_encoding TO 'UTF8' or ?client_encoding=UTF8
MySQLserver character_set_server; connection SET NAMES utf8mb4utf8mb4 in MySQL 8.0+, latin1 in 5.7utf8mb4 everywhere; Laravel 'charset' => 'utf8mb4' in config/database.php
FilesBOM, # coding:, file metadata, or nothingPlatform dependent (locale)UTF-8 without BOM, except Excel CSV (UTF-8 with BOM)
Terminallocale (LANG, LC_ALL), terminal settingC/POSIX or system localeLANG=C.UTF-8 or en_US.UTF-8; Windows chcp 65001
Source codeGo: UTF-8 required; PHP: bytes as writtenn/aSave as UTF-8
EmailContent-Type charset and transfer encodingus-asciiUTF-8, quoted-printable or base64 body; RFC 2047 for headers
Logsno declarationbytes as writtenUTF-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-8

Fix / 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.
ToolDetectConvertNotes
file -I (libmagic)statistical guess, prints charset=noTreat as a hint
iconv -f A -t Bno (validates as a side effect)yes, with //TRANSLIT, //IGNORE suffixes//TRANSLIT output differs between glibc and macOS
uchardet, chardetng, Python charset-normalizeryes, probabilisticnoUse only when you cannot ask the producer
recode, dos2unix, unix2dosnoline endings and code pagesdos2unix fixes CRLF
Go golang.org/x/text/encoding (charmap, unicode, simplifiedchinese, htmlindex)htmlindex.Name resolves labels per WHATWGNewDecoder().String(s) / NewEncoder()Use transform.NewReader for streams
Go utf8 packageutf8.Valid, utf8.ValidStringnoValidate before storing
PHP mbstringmb_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 iconvnoiconv('Windows-1256', 'UTF-8//IGNORE', $s)//IGNORE silently drops bytes
PostgreSQLpg_encoding_to_char, convert_from(bytea, 'LATIN1')convert_to(text, 'WIN1256'), convert(bytea, 'WIN1256', 'UTF8')Server converts to client encoding automatically
MySQLCONVERT(col USING utf8mb4), HEX(col)ALTER TABLE ... CONVERT TO CHARACTER SET utf8mb4A 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 dumpIt means
ef bb bf at offset 0UTF-8 BOM
ff fe or fe ff at offset 0UTF-16 BOM (little / big endian)
Many 00 bytes between ASCII bytesUTF-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 8fZWNJ, ZWJ, RLM: invisible characters inside the text
c3 83 c2 a9double-encoded é (mojibake)
d8 / d9 / da / db lead bytesArabic-script letters in UTF-8 (U+0600-U+06FF)
0d 0aCRLF line ending
ed a0 .. to ed bf ..encoded surrogate: invalid UTF-8
f0 9f startan 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.

ProductNative string modelDefault encodingInvalid UTF-8 handlingNormalization built in?
Gobyte string, UTF-8 by convention; rune is a code pointUTF-8Accepts any bytes; range yields U+FFFD; utf8.ValidString checksNo; golang.org/x/text/unicode/norm
PHPbyte string, no encoding attachedBytes 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 13Illuminate string helpers use mbstringUTF-8Validation rule string accepts bytes; use custom rule or middlewareNo (write a middleware)
JavaScriptUTF-16 code unitsUTF-16Lone surrogates allowed; TextDecoder replaces with U+FFFDString.prototype.normalize
Python 3code point sequenceUTF-8 source; str is Unicodebytes.decode raises UnicodeDecodeErrorunicodedata.normalize
PostgreSQLtext in the database encodingUTF8 recommendedError 22021 invalid byte sequence for encoding "UTF8"normalize() since 13
MySQL 8.4by charsetutf8mb4 (8.0+)Strict mode: error 1366 Incorrect string value; non-strict truncatesNo
SQL Servernvarchar UTF-16; varchar by collationcollation code page; UTF-8 collations in 2019+n/aNo
SQLiteUTF-8 (or UTF-16)UTF-8Stores bytes; functions assume UTF-8No
Redisbinary-safe stringsn/anoneNo
ElasticsearchJSON UTF-8; analyzers on tokensUTF-8rejects invalid JSONICU analysis plugin (icu_normalizer, icu_folding)

Languages for the same operations.

OperationGoPHP / Laravel
Iterate code pointsfor i, r := range smb_str_split($s)
Count code pointsutf8.RuneCountInString(s)mb_strlen($s, 'UTF-8'), Str::length($s)
Substring by code pointsstring([]rune(s)[a:b])mb_substr($s, $a, $n, 'UTF-8'), Str::substr
Validate UTF-8utf8.ValidString(s)mb_check_encoding($s, 'UTF-8')
Replace invalid bytesstrings.ToValidUTF8(s, string(utf8.RuneError))mb_convert_encoding($s, 'UTF-8', 'UTF-8') or iconv('UTF-8', 'UTF-8//IGNORE', $s)
Normalize NFCnorm.NFC.String(s)Normalizer::normalize($s, Normalizer::FORM_C)
Lower-casestrings.ToLower(s); cases.Lower(language.Turkish)mb_strtolower($s, 'UTF-8'), Str::lower($s)
Byte orderbinary.BigEndian / LittleEndianpack('N') / pack('V')
Transliterate to ASCIIgolang.org/x/text/transform with norm.NFD and a filterStr::ascii($s), iconv('UTF-8', 'ASCII//TRANSLIT', $s), transliterator_transliterate('Any-Latin; Latin-ASCII', $s)
Graphemesuniseggrapheme_strlen

Databases for string rules.

ProductUTF-8 storage typeMax index key / length notesRecommended collation approachlength function
PostgreSQLtext, varchar(n) in a UTF8 databasevarchar(n) n up to 10,485,760 characters; btree entries are limited by page sizeICU collation or citext or normalized key columnlength, octet_length
MySQL / InnoDButf8mb4Row size 65,535 bytes; index prefix 3072 bytes (DYNAMIC)utf8mb4_0900_ai_ci or utf8mb4_unicode_ci; _bin for exactCHAR_LENGTH, LENGTH
MariaDButf8mb4similarchoose by versionsame
SQL Servernvarchar or UTF-8 varchar collation900-byte clustered, 1700-byte nonclustered index keysLatin1_General_100_CI_AS_SC_UTF8LEN (characters, trims trailing spaces), DATALENGTH bytes
OracleNVARCHAR2 or AL32UTF8 databaseVARCHAR2 max 4000 bytes (32767 extended)NLS_SORTLENGTH, LENGTHB
SQLiteTEXTnone enforcedCOLLATE NOCASE is ASCII-onlylength() characters, length(CAST(x AS BLOB)) bytes
MongoDBBSON string, UTF-816 MiB documentcollation option per collection/index (ICU)$strLenCP, $strLenBytes
CockroachDBUTF-8 STRINGlike PostgreSQLICU collation via COLLATElength, octet_length
Redisbinary-safe512 MB valuen/aSTRLEN bytes

Mechanics ​

The UTF-8 decoder, step by step Important ​

  1. Read byte b0. If b0 < 0x80, emit it (1 byte).
  2. If 0xC2 <= b0 <= 0xDF, expect 1 continuation byte; if 0xE0 <= b0 <= 0xEF, 2; if 0xF0 <= b0 <= 0xF4, 3. Bytes 0x80-0xBF (stray continuation), 0xC0, 0xC1 and 0xF5-0xFF never start a sequence.
  3. Each continuation byte must be 10xxxxxx (0x80-0xBF), with tighter bounds on the second byte for E0 (A0-BF), ED (80-9F, to exclude surrogates), F0 (90-BF) and F4 (80-8F, to stay under U+10FFFF).
  4. Combine payload bits; the result must be at least the minimum for its length (that rejects overlong forms such as C0 80).
  5. 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 ​

WhereMessage or codeMeaningFix
PostgreSQLERROR: 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
PostgreSQLcharacter with byte sequence 0xd8 0xb3 in encoding "UTF8" has no equivalent in encoding "LATIN1" (22P05)Server encoding or client_encoding cannot hold the characterUse UTF8 everywhere
PostgreSQLinvalid byte sequence for encoding "UTF8": 0x00NUL bytes are not allowed in textStrip \0 or use bytea
MySQLERROR 1366 (HY000): Incorrect string value: '\xF0\x9F\x98\x80' for column 'name' at row 1Column charset cannot store the character (usually utf8mb3)Convert column to utf8mb4
MySQLERROR 1300 (HY000): Invalid utf8mb4 character stringInvalid bytes in a literalValidate input
MySQLERROR 1267 Illegal mix of collationsComparing columns or literals with different collationsAlign collations or use COLLATE
MySQLERROR 1264 Out of range value for columnNumeric overflow in strict modeWiden the type
PostgreSQLERROR: integer out of range (22003)Arithmetic overflowbigint or numeric
iconviconv: iconv(): Illegal byte sequenceInput invalid for the source charsetFix the source charset label
iconviconv: unexpected end of file; the last character is incomplete.Truncated multi-byte characterFind where the stream was cut
PHPjson_encode returns false, json_last_error_msg() is Malformed UTF-8 characters, possibly incorrectly encodedInvalid UTF-8 in a stringmb_convert_encoding, JSON_INVALID_UTF8_SUBSTITUTE
PHPmb_substr(): ... no error; substr silently cuts bytesByte function on UTF-8Use mb_*
Goinvalid UTF-8 is not an error; json.Marshal replaces invalid bytes with U+FFFDLenient by designValidate with utf8.ValidString where it matters
Gox/text encoder: encoding: rune not supported by encoding.Target charset cannot represent the runeUse encoding.ReplaceUnsupported or UTF-8
HTTP406, 415 for charset or content negotiationRare for UTF-8; check Accept-CharsetServe UTF-8

Solving the classic problems ​

ProblemTypical symptomSolutionHowAdvantageCost or limitation
Double encoding / mojibakeé, سلامFix at the producer; repair stored data onceDecode with the wrong charset then re-decode as UTF-8Data restored when no byte was lostImpossible if a lossy conversion (?) happened
Truncation mid-code-point\xd9 at the end, Malformed UTF-8Truncate at a rune boundaryutf8.RuneStart loop (Go), mb_strcut (PHP)Always-valid UTF-8A display limit should still use graphemes
Mixed yeh/kaf breaks searchکتاب finds nothingSearch key column with a Persian mapPersianNormalizer::searchKey, persian.SearchKey, translate() in SQLMatches whichever keyboard typed itOne more column to keep in sync
Look-alike or duplicate usernamesTwo accounts that look the sameNFKC + case fold + ASCII or script allow-list; unique index on the keyCanonicalize then validateBlocks confusablesPolicy decisions (which scripts)
Invisible ZWNJ/RLM in IDs"Username taken" but not findableReject Cf characters in identifiers; strip in search keyspreg_match('/\p{Cf}/u') / unicode.Is(unicode.Cf, r)Predictable identifiersLegitimate ZWNJ stays allowed in names
NFC vs NFD file namescafé.txt exists but is not foundNormalize names to NFC at your boundarynorm.NFC.String(name)Same name everywhereLookups on macOS need both forms
Excel opens UTF-8 CSV as garbageسلام in ExcelWrite a UTF-8 BOM firstEF BB BF prefixExcel auto-detectsOther parsers must strip the BOM
Integer or float surprises0.30000000000000004, 2038 wrapIntegers for money; int64; tolerance for floatsint64 cents, bigint, numericExactConversions 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:

sql
-- 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:

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.

sql
-- 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):

go
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
<?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
<?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:

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
<?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
<?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:

go
// 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 name

Transliteration 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
<?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 sequence

File 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:

go
w.Write([]byte{0xEF, 0xBB, 0xBF}) // UTF-8 BOM so Excel detects UTF-8
csv.NewWriter(w).WriteAll(rows)
php
return response("\xEF\xBB\xBF" . $csv, 200, ['Content-Type' => 'text/csv; charset=UTF-8']);

Choosing ​

SituationChooseExtra techniqueReason
New project, any storageUTF-8 everywhere (utf8mb4, PostgreSQL UTF8)Validate at the edgeOne encoding, ASCII-compatible, the web's default
MySQL tables from the 5.x eraConvert to utf8mb4ALTER TABLE ... CONVERT TO CHARACTER SET utf8mb4, check index key lengthsutf8/utf8mb3 drops emoji and U+10000+
Windows APIs, Java, JavaScript interopUTF-16 only at the boundaryAlways label LE/BE or use a BOMTheir native string unit
Binary wire format (custom, RPC)Big-endian (network order) or a schema formatDocument the order; test with xxdInterop with other languages and CPUs; or use Protobuf and friends
Storing text for displayNFC, keep ZWNJCanonical form onlyLossless
Matching or de-duplicating textSeparate lossy key (NFKC, folding, Persian map)Same function on index and queryPredictable matching without damaging the display value
MoneyInteger minor units or numericNever floatExactness
IDs from JavaScript clientsStrings for 64-bit integersbigint in storageNumbers beyond 2^53 lose precision
Length limit for usersGraphemes (or code points)Bytes at the storage layerWhat a person counts vs what the row holds
Legacy import (Windows-1256)Convert once at ingestKeep original bytes and the declared charsetIdempotent, debuggable
Excel-facing CSVUTF-8 with BOMOr UTF-16LE with BOM tab-separatedExcel's detection rules
PasswordsNFKC before hashing (NIST SP 800-63B)Hash the bytesSame 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.

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 ​

ScaleWhat changes for text and bytesAction
1x (one app, one database)Encoding settings and a normalization functionutf8mb4/UTF8, middleware, search key column
10x (replicas, cache, queue)Many readers and writers must agreeShared 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 costHash 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 ​

SymptomLikely causeCheckFix
é instead of éUTF-8 read as Latin-1/cp1252xxd shows c3 a9; reader label says latin1Decode as UTF-8; fix the charset
? where Persian letters should beStored in a narrow charset (lossy)Column charset; SHOW CREATE TABLE; hex of the stored value shows 3fConvert column to utf8mb4; re-import
Incorrect string value: '\xF0\x9F...'utf8mb3 columnSHOW CREATE TABLE usersALTER TABLE ... CONVERT TO CHARACTER SET utf8mb4
invalid byte sequence for encoding "UTF8"Latin-1 or truncated bytes sent to PostgreSQLHex of the offending valueConvert or validate at the edge
json_encode returns falseInvalid UTF-8 (often from substr)mb_check_encodingUse mb_substr/mb_strcut
Search for کتاب finds nothingArabic kaf/yeh in data or queryHex of both strings: 06A9 vs 0643Search key column
Two users "the same" but both allowedNFC vs NFD or look-alikesCompare NFC/NFKC formsNormalize before the unique check
Username "taken" but not foundInvisible RLM/ZWNJ/BOMxxd shows e2 80 8f/e2 80 8c/ef bb bfStrip bidi and Cf in identifiers
Persian text order reversed or scrambledVisual-order data or bidi controlsAre there U+202x/U+2066..2069 controls?Store logical order; use dir="rtl" or <bdi> in HTML
Digits ۱۲۳ rejected by validationPersian digits vs ASCII-only ruleCode points U+06F1..Convert with Digits for numeric fields
Excel shows garbageCSV without BOMFirst bytes of the fileAdd EF BB BF
File café.txt not found on LinuxNFD name from macOS`lsxxdshows65 cc 81`
Counter or ID suddenly negative or 0Integer overflow or wrong widthColumn type; bit widthWiden type; check before arithmetic
Packets parse with wrong valuesByte order mismatchDump bytes; compare with the specbinary.BigEndian / pack('N')
Same query sorts differently after upgradeICU/glibc collation version changepg_collation_actual_version; REINDEXPin collation, reindex
Emoji split or truncatedCutting at bytes or code pointsutf8.ValidString; graphemesTruncate 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.

bash
cd docs/snippets/foundations/bits-bytes-text-encoding/go
go vet ./... && go test ./...          # all snippets compile; the persian tests pass

1. The same Persian word in UTF-8 and UTF-16, in hex.

bash
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 | xxd
00000000: 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 bytes

Question: 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.

bash
go run ./runes

Expected: 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.

bash
go run ./norm
printf 'caf\xc3\xa9' | xxd ; printf 'cafe\xcc\x81' | xxd
00000000: 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.

bash
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.30000000000000004

5. Mixed yeh/kaf search bug in PostgreSQL, and the fix.

sql
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
-- ------------
--  t

Then 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).

bash
echo -n "سلام می‌خواهم" | hexdump -C

Find 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 ​

BeliefReality
"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 ​

TopicWhat to remember
LayersGrapheme cluster, code point, code unit, byte: count the layer the rule is about
UTF-8 patterns0xxxxxxx, 110xxxxx 10xxxxxx, 1110xxxx 10xxxxxx 10xxxxxx, 11110xxx plus three continuations
Persian in UTF-8Letters in U+0600-U+06FF take 2 bytes; ZWNJ e2 80 8c; Persian yeh db 8c, Arabic yeh d9 8a
Byte orderNetwork order is big-endian; binary.BigEndian, pack('N'), htonl; x86 and ARM are little-endian
IntegersTwo's complement; overflow wraps in Go; PHP turns into float; use bigint and int64
FloatsIEEE 754; never ==; money in integers or numeric
BOMEF BB BF UTF-8, FF FE UTF-16LE, FE FF UTF-16BE; JSON must not have one
NormalizationNFC for storage; NFKC plus fold plus Persian map for search keys; NFKC is lossy
Yeh and kafMap U+064A, U+0649 to U+06CC and U+0643 to U+06A9; neither NFC nor NFKC does it
Length functionsGo len, PHP strlen: bytes. mb_strlen, utf8.RuneCountInString: code points. grapheme_strlen, uniseg: graphemes
MySQLutf8mb4 always; utf8 is utf8mb3; error 1366 is the symptom
PostgreSQLUTF8 encoding; client_encoding; normalize(); varchar(n) counts characters
BoundariesDeclare UTF-8 on HTTP, DB connection, files and terminals; JSON is UTF-8
Hex dumpxxd, hexdump -C: dump the bytes first when text looks wrong
TruncationCut at rune or grapheme boundaries: utf8.RuneStart, mb_strcut, grapheme_substr
Conversioniconv -f A -t B, x/text/encoding/charmap, mb_convert_encoding; keep original bytes

Self-check: questions & answers ​

Show:
  • 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 ​

TermDefinition
BitOne binary digit, 0 or 1
Nibble4 bits, one hex digit
Byte / octet8 bits; the smallest addressable unit
WordThe natural integer size of a CPU or format; varies
Two's complementSigned integer representation; negate by inverting and adding 1
Overflow / wrap-aroundResult exceeds the type's range; Go discards high bits
IEEE 754The standard for binary floating-point numbers (float32, float64)
NaN"Not a number"; never equal to itself
EndiannessOrder of bytes of a multi-byte number in memory or on the wire
Big-endianMost significant byte first; network byte order
Little-endianLeast significant byte first; x86, ARM (default)
htons / htonlConvert 16/32-bit values from host to network byte order
Character setA set of characters with numbers
EncodingA mapping from code points to bytes
Code pageA legacy charset and encoding in one (Windows-1252, Windows-1256)
ASCII7-bit character set, values 0-127
ISO 8859-1 (Latin-1)8-bit Western European encoding
Windows-1252Latin-1 variant with printable characters at 0x80-0x9F
MojibakeGarbled text from decoding with the wrong encoding
UnicodeThe universal character set, U+0000 to U+10FFFF
Code pointA number assigned to a character, written U+XXXX
PlaneA block of 65,536 code points; 17 in total
BMPBasic Multilingual Plane, U+0000-U+FFFF
SurrogateU+D800-U+DFFF; UTF-16's trick for code points above U+FFFF
Scalar valueA code point that is not a surrogate
UTF-8Variable-width encoding, 1-4 bytes per code point
UTF-162 or 4 bytes per code point (a surrogate pair)
UTF-324 bytes per code point
BOMU+FEFF at the start of a stream; EF BB BF in UTF-8
Overlong encodingNon-shortest UTF-8 form (for example C0 80); invalid
Self-synchronisingYou can find a character boundary from any byte
Replacement characterU+FFFD, emitted for invalid input
Grapheme clusterA user-perceived character, per UAX #29
ZWJU+200D ZERO WIDTH JOINER; forces joining and glues emoji
ZWNJU+200C ZERO WIDTH NON-JOINER; prevents joining in Persian
RLM / LRMU+200F / U+200E invisible direction marks
BidiBidirectional text (right-to-left and left-to-right mixed)
Tatweel (kashida)U+0640; elongation line, decoration only
HarakatArabic vowel marks U+064B-U+065F
Presentation formsPre-shaped Arabic glyph code points (U+FB50-U+FDFF, U+FE70-U+FEFF)
Yeh, kafLetters with Arabic (U+064A, U+0643) and Persian (U+06CC, U+06A9) code points
NormalizationRewriting equivalent text to one form (NFC, NFD, NFKC, NFKD)
Canonical equivalenceSame abstract character, same appearance and behavior
Compatibility equivalenceSame text with formatting differences (ligatures, fullwidth)
Case foldingMapping for caseless comparison (ß to ss)
CollationRules for comparing and sorting strings
Deterministic collationEqual only if the bytes are equal (PostgreSQL term)
utf8mb4MySQL's real UTF-8, up to 4 bytes per character
utf8mb3MySQL's 3-byte subset, alias utf8 (deprecated)
client_encodingPostgreSQL session setting for the client's encoding
mb_strlen / strlenPHP code point count / byte count
iconvCommand and library for converting encodings
Hex dumpByte-by-byte view (xxd, hexdump -C)
unisegGo module for grapheme, word and sentence segmentation
x/textGo extended text packages: encodings, normalization, collation, cases

References ​

Built by Morteza Negahi