5 Module N_HEX
gullradriel edited this page 2026-10-09 00:55:18 +02:00

HEX: hexadecimal encode and decode

Functions

Name
size_t n_hex_encode_to(char * out, size_t out_size, const unsigned char * data, size_t len)
encode len bytes of data as lowercase hex into the caller-provided buffer out (needs out_size >= 2*len+1), NUL-terminating on success.
N_STR * n_hex_encode(const unsigned char * data, size_t len)
encode len bytes of data as a lowercase hex N_STR (2*len characters); free with free_nstr.
int n_hex_decode_to(unsigned char * out, size_t out_size, const char * hex, size_t nbytes)
decode exactly nbytes bytes from the first 2*nbytes hex digits of hex (case-insensitive, no embedded whitespace) into the caller-provided buffer out (needs out_size >= nbytes).
unsigned char * n_hex_decode(const char * hex, size_t * out_len)
decode a hex string (ASCII whitespace between digits is ignored) into a freshly allocated, NUL-terminated byte buffer; *out_len receives the decoded byte count.

Functions Documentation

function n_hex_encode_to

size_t n_hex_encode_to(
    char * out,
    size_t out_size,
    const unsigned char * data,
    size_t len
)

encode len bytes of data as lowercase hex into the caller-provided buffer out (needs out_size >= 2*len+1), NUL-terminating on success.

Zero-allocation variant of n_hex_encode. Returns the number of hex characters written (2*len), or 0 on a NULL out, NULL/oversized data, or a too-small buffer (out left untouched).

function n_hex_encode

N_STR * n_hex_encode(
    const unsigned char * data,
    size_t len
)

encode len bytes of data as a lowercase hex N_STR (2*len characters); free with free_nstr.

Returns NULL on a NULL/oversized input or on allocation failure.

function n_hex_decode_to

int n_hex_decode_to(
    unsigned char * out,
    size_t out_size,
    const char * hex,
    size_t nbytes
)

decode exactly nbytes bytes from the first 2*nbytes hex digits of hex (case-insensitive, no embedded whitespace) into the caller-provided buffer out (needs out_size >= nbytes).

Zero-allocation, fixed-length counterpart to n_hex_decode. Returns TRUE on success, FALSE on a too-small buffer, a hex string shorter than 2*nbytes, or an invalid hex digit.

function n_hex_decode

unsigned char * n_hex_decode(
    const char * hex,
    size_t * out_len
)

decode a hex string (ASCII whitespace between digits is ignored) into a freshly allocated, NUL-terminated byte buffer; *out_len receives the decoded byte count.

Free the buffer with Free()/free(). Returns NULL on an odd number of hex digits or an invalid character.