Encodings

Hex

Hex for bytes or Unicode code points. Your puzzle gets to choose
IDhex05 / 20hex · 16 characters
Encoding / Hex

Hex (Base16)

Two digits a byte. The one everybody reads.

Overhead
+100% on random bytes
Padding
none
Standard
RFC 4648 §8; Unicode code points
Family
1 in hex
family 1 / 20

Sample

Out
68656c6c6f20776f726c6421
Back
"hello world!"

Options

codepointsboolean
default false
Each number is a Unicode code point of UTF-8 text, such as U+017C or 17c for ż; encoding writes U+017C
upperboolean
default false
Write A-F instead of a-f

Access

Importimport { hex } from "@agntn/encodings/hex"
CLIencodings encode hex 'hello world!'
Tryplayground with the sample above

Two digits a byte. The encoding everybody already reads without thinking.

ts
encode("hex", "gm");                   // "676d"
encode("hex", "gm", { upper: true });  // "676D"
decode("hex", "0x67 6D").bytes;        // Uint8Array [103, 109]

Decoding takes either case. It drops one leading 0x and skips spaces and line breaks. So a hex dump pastes straight in. An odd number of digits? Error. Half a byte isn't a byte.

What if that hex is a character?

Set codepoints: true to read each number as one Unicode code point. The result is text as UTF-8 bytes. Unicode charts already speak this language. That's a nice shortcut.

ts
decode("hex", "U+005A U+0061 U+017C", { codepoints: true }).bytes;  // Uint8Array [90, 97, 197, 188], "Zaż"
encode("hex", "Zażółć", { codepoints: true });  // "U+005A U+0061 U+017C U+00F3 U+0142 U+0107"

On decode, U+ is optional and letter case doesn't matter. Use any number of digits, with leading zeros if you like. Separate numbers with spaces, commas or line breaks.

Encoding takes UTF-8 text and writes uppercase numbers with U+. Each has at least four digits, with spaces between them. The upper option gets no say here. 🎉 comes out as U+1F389.

What happens without codepoints? 017c becomes two bytes, not one ż.

ts
decode("hex", "017c").bytes;                        // Uint8Array [1, 124]
decode("hex", "017c", { codepoints: true }).bytes;  // Uint8Array [197, 188], ż in UTF-8

The decoder refuses values over U+10FFFF and surrogates from U+D800 to U+DFFF. The error gives the index. So U+D83C U+DF89, the UTF-16 halves of 🎉, won't work. Use the whole code point, U+1F389.

In byte mode, U+017C fails. The error ends with for Unicode code points, such as U+017C for ż, set codepoints.