Skip to content

encoding.hex #

Description

encoding.hex converts between byte arrays and hexadecimal strings.

hex.encode emits lowercase digits by default. Set uppercase: true for uppercase digits and with_prefix: '0x' to prepend a prefix. The prefix is also emitted for empty input:

import encoding.hex

assert hex.encode([u8(0xab), 0xcd]) == 'abcd'
assert hex.encode([]u8{}, with_prefix: '0x') == '0x'
assert hex.encode([u8(0xab)], uppercase: true, with_prefix: '0X') == '0XAB'

hex.decode accepts either case and an optional 0x or 0X prefix. An odd number of digits is decoded as if the first digit had a leading zero. Invalid digits return an error.

fn decode #

@[direct_array_access]
fn decode(s string) ![]u8

decode converts a hex string into an array of bytes. The expected input format is 2 ASCII characters for each output byte. If the provided string length is not a multiple of 2, the first digit is decoded as if an implicit 0 preceded it. An optional 0x or 0X prefix is accepted.

fn encode #

@[direct_array_access]
fn encode(bytes []u8, params EncodeParams) string

encode converts an array of bytes into a string of ASCII hex bytes. The hex portion has two characters per input byte. If EncodeParams.uppercase is set, the output hex characters are emitted in uppercase. If EncodeParams.with_prefix is non-empty, the output string is prefixed with the provided string, including when the input is empty.

struct EncodeParams #

@[params]
struct EncodeParams {
pub mut:
	uppercase   bool
	with_prefix string
}

EncodeParams configures optional output formatting for encode.

If uppercase is set, encode emits A-F instead of a-f. If with_prefix is non-empty, encode prepends that exact string.