Belajar
← All lessons

How UTF-8 works

From a character to bytes

encode.js

function encodePoint(cp) {  // ASCII stays one byte, so old ASCII text is already UTF-8  if (cp <= 0x7f) return [cp];  // 110 means: me and 1 more byte  if (cp <= 0x7ff) return [0xc0 | (cp >> 6),                           0x80 | (cp & 0x3f)];  // 1110: me and 2 more  if (cp <= 0xffff) return [0xe0 | (cp >> 12),                            0x80 | ((cp >> 6) & 0x3f),                            0x80 | (cp & 0x3f)];  // 11110: me and 3 more, enough for every emoji  return [0xf0 | (cp >> 18),          0x80 | ((cp >> 12) & 0x3f),          0x80 | ((cp >> 6) & 0x3f),          0x80 | (cp & 0x3f)];}

decode.js

function charLength(lead) {  if (lead >> 7 === 0b0) return 1;  if (lead >> 5 === 0b110) return 2;  if (lead >> 4 === 0b1110) return 3;  if (lead >> 3 === 0b11110) return 4;  throw new Error("continuation byte");}

Count your own text four answers to one question

Text
Or try
0characters you see
0code points
0JS .length
0UTF-8 bytes
Character by character

lengths.js

const s = "👋🏽";// UTF-16 code units: emoji count as 2s.length;// code points: a family emoji is still 5[...s].length;// what a person calls a character[...new Intl.Segmenter().segment(s)].length;// what it costs to store or sendnew TextEncoder().encode(s).length;

Cut at a byte limit and break a character

Keep the first14 bytes
Bytes "aé€👋🏽"
Cut right there
Back up to a character start

truncate.js

function truncateBytes(text, max) {  const bytes = new TextEncoder().encode(text);  let n = Math.min(max, bytes.length);  // back up past continuation bytes (10xxxxxx)  while (n > 0 && (bytes[n] & 0xc0) === 0x80) n--;  return new TextDecoder().decode(bytes.slice(0, n));}

Topics

Next: How base64 works

Open lesson