Skip to content
Effect Days 2026 Get your ticket

Hex

Hexadecimal encoding, decoding, and random value helpers.

4 exports Added in v4.0.0 Source

Decoding

decode

Added in v4.0.0 Source

Decodes a hexadecimal string into bytes safely.

When to use

Use to decode hexadecimal text into bytes without throwing on invalid input.

Details

Returns Result.succeed with a Uint8Array when decoding succeeds, or Result.fail with an EncodingError when the input has an odd length or contains invalid hex characters.

Signature

declare function decode(str: string): Result<Uint8Array<ArrayBufferLike>, EncodingError>

Example

(Decoding hex bytes)

import { Result } from "effect"
import { Hex } from "effect/encoding"
Hex.decode("48656c6c6f") // => Result.succeed(new Uint8Array([72, 101, 108, 108, 111]))

decodeString

Added in v4.0.0 Source

Decodes a hexadecimal string into a UTF-8 string safely.

When to use

Use to decode hexadecimal text into UTF-8 text without throwing on invalid input.

Details

Returns Result.succeed with the decoded text when decoding succeeds, or Result.fail with an EncodingError when the input is not valid hex.

Signature

declare function decodeString(str: string): Result<string, EncodingError>

Example

(Decoding hex strings)

import { Result } from "effect"
import { Hex } from "effect/encoding"
Hex.decodeString("68656c6c6f") // => Result.succeed("hello")

Encoding

encode

Added in v4.0.0 Source

Encodes the given value into a hex string.

When to use

Use to encode text or bytes as lowercase hexadecimal text.

Signature

declare const encode: (input: Uint8Array | string) => string

Example

(Encoding hex strings and bytes)

import { Hex } from "effect/encoding"
// Encode a string to hex
Hex.encode("hello") // => "68656c6c6f"
// Encode binary data to hex
const bytes = new Uint8Array([72, 101, 108, 108, 111])
Hex.encode(bytes) // => "48656c6c6f"

random

Added in v4.0.0 Source

Generates a random lowercase hexadecimal string, optimized for lengths that are multiples of 8.

Details

length is not validated. The function generates length >>> 3 random 8-character words, so non-negative lengths below 2 ** 32 are rounded down to a multiple of 8 and other values follow JavaScript's unsigned 32-bit coercion rules.

This function uses Math.random() and is not cryptographically secure. For security-sensitive values, use the Crypto.Crypto service's randomBytes method and encode the result with encode.

Signature

declare function random(length: number): string