Hex

class Hex extends Object

Converts binary data to and from hexadecimal text. Call both methods on the class itself.

#Import Ks { Hex }

Encode

Text := Hex.Encode(Value , Encoding := "UTF-8")

Value is a String, StringBuffer or Buffer. Text uses Encoding, whose names match FileEncoding. A Buffer retains its bytes. Returns uppercase hexadecimal, two digits per byte, without separators or a 0x prefix. Empty input returns an empty String.

An unrecognized encoding raises ValueError; an input which holds no bytes raises TypeError.

Decode

Bytes := Hex.Decode(Text)

Returns a Buffer containing the decoded bytes. Text must contain an even number of hexadecimal digits, using 0-9 and A-F in either letter case. Empty text returns an empty Buffer.

Odd lengths, whitespace, prefixes such as 0x and other invalid characters raise ValueError.

To interpret the resulting bytes as text, call StrGet with the encoding of the original data.

Examples

Converts text to hexadecimal and reads it back.

#Import Ks { Hex }
Encoded := Hex.Encode("Hello") ; 48656C6C6F
Bytes := Hex.Decode("48656c6c6f")
FileAppend StrGet(Bytes, Bytes.Size, "UTF-8"), "*"

Obtains raw HMAC digest bytes. The complete TOTP example uses this conversion for dynamic truncation.

#Import Ks { Crypt, Hex }
Digest := Hex.Decode(Crypt.Hmac("message", "key"))
FirstByte := NumGet(Digest, 0, "UChar")

Base32, Base64, Crypt, Buffer, StrGet