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
Sample
- Out
- 68656c6c6f20776f726c6421
- Back
- "hello world!"
Options
Access
- Import
import { hex } from "@agntn/encodings/hex" - CLI
encodings encode hex 'hello world!' - Tryplayground with the sample above
Two digits a byte. The encoding everybody already reads without thinking.
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.
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 ż.
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.