---
title: "Hex"
description: "Hex for bytes or Unicode code points. Your puzzle gets to choose"
canonical_url: "https://encodings.agntn.dev/encodings/hex"
---
# Hex

> Hex for bytes or Unicode code points. Your puzzle gets to choose

<encoding-facts name="hex">



</encoding-facts>

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


## Sitemap

See the full [sitemap](https://encodings.agntn.dev/sitemap.md) for all pages.
