Bits, floats, text and encodings

O(1)·O(1) space
Fit

Drag to pan; pinch or Ctrl+scroll to zoom; arrow keys pan once the picture has focus.

Nothing has been aligned yet.

The character "😀" is codepoint U+1F600, which needs 4 UTF-8 bytes.

The character "😀" is codepoint U+1F600, which needs 4 UTF-8 bytes.
  1. 1read the codepoint and decide how many bytes it needs
  2. 2write the first byte: header bits announcing the count, then the leading payload bits
  3. 3write each remaining byte: the fixed 10 marker, then six more payload bits
  4. 4decode: strip every header and continuation marker and concatenate what is left
Bytes processed
1

Complexity

BestO(1)
AverageO(1)
WorstO(1)
Extra spaceO(1)
bytes touched at n=1 predicts 1; this run took 1.

UTF-8

UTF-8 encodes a Unicode codepoint into one to four bytes. The first byte’s own leading bits announce how many bytes the whole sequence has (0 for one byte, 110 for two, 1110 for three, 11110 for four); every byte after the first starts with the fixed marker 10, leaving six payload bits each. The codepoint’s own bits are distributed across whatever payload positions are available, most significant bits first.

When it is the right choice

The encoding essentially every modern text format and network protocol uses for Unicode, specifically because it is backward-compatible with plain ASCII (every ASCII byte is already a valid one-byte UTF-8 sequence) and self-synchronising (a decoder can tell from any single byte, on its own, whether that byte starts a sequence or continues one).

How it works

Worth noticing

Cost

Best
O(1)
Average
O(1)
Worst
O(1)
Extra space
O(1)

All bits algorithms